【问题标题】:Java Iterator Interface remove() method. how it will work and produce expected resultJava 迭代器接口 remove() 方法。它将如何工作并产生预期结果
【发布时间】:2022-12-13 19:44:17
【问题描述】:

我想知道这个 Iterator remove() 是如何工作的

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); list.add(2); list.add(3); list.add(4);

Iterator<Integer> it = list.iterator();

while(it.hasNext()){
    int x = it.next();
    if(x%2==0) it.remove();
    else System.out.println(x+" ");
}
 o/p : 1 3

这种方法如何工作?如果 remove() 任何元素。它从数组中删除并向右移动?我尝试了集合中存在的其他选项 remove(index) 或 remove(object) 方法它会导致异常任何 Java 专家请解释并提及 Iterator 接口中存在的此方法 remove() 的时间复杂度

【问题讨论】:

  • 这更多是关于您的代码中使用其他方法消除的错误,而不是其他任何事情——但除非您向我们展示该代码,否则我们无法真正解释这些错误,因此我们可以识别确切的错误。
  • 真的“左”和“右”在一个数组中是没有意义的。它向索引 0 移动。我怀疑大多数人(至少说英语的人)会认为索引 0 是最左边的,在这种情况下它正在移动剩下.时间复杂度为 O(n^2)。对集合进行 N 次迭代,每次删除都需要 N 次操作来移动所有内容。在 LinkedList 中,它将是 O(n),因为删除只涉及设置几个指针并且是常数时间

标签: java arraylist collections iterator time-complexity


【解决方案1】:

ArrayList 类有一个名为Itr 的类。 Itr实现了Iterator接口的remove()方法,像这样:

public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

在那里:

  • lastRet - 最后从next()返回元素数组的索引
  • cursor - 当前元素的索引

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多