java - 为什么这个 for 循环不起作用?

标签 java for-loop

所以我必须创建一个名为 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/

相关文章:

java - 如何使用 Java 在屏幕上移动 Windows 窗口?

javascript - 如何随机生成数字?

c++ - 使用 Opencv C++ 对循环进行矢量化

java - 使 mongoClient 对象/任何对象在应用程序中可用

java - Java Swing 应用程序中类似 Qtip 的气泡

java - 降低代码的复杂性

c++ - BOOST_FOREACH 与 for 循环

java - m2e 也可以配置为下载插件源吗?

python - 在文件中查找彼此相反的单词

c++ - for 循环在 if 条件下