有一种更简单的方法可以解决这个问题,而无需创建新的迭代器对象。这是概念。假设您的 arrayList 包含一个名称列表:
names = [James, Marshall, Susie, Audrey, Matt, Carl];
要从 Susie 中删除所有内容,只需获取 Susie 的索引并将其分配给一个新变量:
int location = names.indexOf(Susie);//index equals 2
现在你有了索引,告诉 java 计算你想从 arrayList 中删除值的次数:
for (int i = 0; i < 3; i++) { //remove Susie through Carl
names.remove(names.get(location));//remove the value at index 2
}
每次循环值运行时,arrayList 的长度都会减少。由于您已经设置了索引值并且正在计算删除值的次数,因此您已经准备就绪。以下是每次通过后的输出示例:
[2]
names = [James, Marshall, Susie, Audrey, Matt, Carl];//first pass to get index and i = 0
[2]
names = [James, Marshall, Audrey, Matt, Carl];//after first pass arrayList decreased and Audrey is now at index 2 and i = 1
[2]
names = [James, Marshall, Matt, Carl];//Matt is now at index 2 and i = 2
[2]
names = [James, Marshall, Carl];//Carl is now at index 3 and i = 3
names = [James, Marshall,]; //for loop ends
以下是您的最终方法的一个片段:
public void remove_user(String name) {
int location = names.indexOf(name); //assign the int value of name to location
if (names.remove(name)==true) {
for (int i = 0; i < 7; i++) {
names.remove(names.get(location));
}//end if
print(name + " is no longer in the Group.");
}//end method