所以我必须创建一个名为 mylistofstrings 的类,它听起来就是一个字符串数组。我必须编写的方法之一是保留所有方法,它只保留列表中等于作为参数输入的字符串的字符串。 for 循环似乎跳过了它应该删除的一半内容,有什么想法吗? size 方法只返回列表中有多少个元素,发布起来很简单。
public boolean retain(String string) {
if (string == null) {
throw new NullPointerException();
}
MyListOfStrings temp= new MyListOfStrings(this);
int t=this.size();
for (int i=0;i<this.size;i++){
if (string.equals(temp.get(i))!=true){
this.remove(i);
}
}
return t<this.size();
这是获取方法:
public String get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
return strings[index];
}
和删除方法:
public String remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
String temp = strings[index]; // Save to return at end
System.arraycopy(strings, index + 1, strings, index, size - index - 1);
strings[size - 1] = null;
size--;
return temp;
}
最佳答案
您在遍历数组的同时更改了数组的内容。当移除位置 x 的项目时,位置 x+1 的项目将获得新的位置 x,但由于 x 已经被循环访问过,因此下一次迭代将是位置 x+1,而现在持有位置的项目x 将被跳过。
您需要执行如下所示的操作:removing items from list in java
即实现 Iterable
,并使用 Iterator
关于java - 为什么这个 for 循环不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019463/