简体   繁体   English

从Java中的列表中删除项目

[英]Removing an item from a list in Java

I've scoured this site (as well as the web) and for some reason cannot find an answer that works. 我已经搜索了该网站(以及网络),并且由于某种原因找不到有效的答案。 Either I get an index out of bounds error, or the next part of my code won't execute. 我得到一个超出范围的索引错误,或者我的代码的下一部分将无法执行。 All I am trying to do is remove a item from a list in Java using an iterator. 我要做的就是使用迭代器从Java列表中删除一个项目。 Here is my code: 这是我的代码:

public boolean remove(T item) {
    while (bag.iterator().hasNext()) {
        T i = bag.iterator().next();
            if (i.equals(item)) {
                bag.iterator().remove();
                return true;
            }
    }
  return false;
}

My iterator inherits from my "Bag" class obviously, but here it is as well: 我的迭代器显然是从“ Bag”类继承的,但在这里也是如此:

public Iterator<T> iterator() {
    return new Iterator<T>() {
        private int current = 0;

        public boolean hasNext() {
            return current < size;
        }

        public T next() {
            return data[current++];
        }

        public void remove() {
            for (int i=current-1; i<size-1; i++)
                data[i] = data[i+1];
            size--;
        }
    };
}

Any help is much appreciated, thanks guys!! 非常感谢任何帮助,谢谢大家!!

Clayton 克莱顿

Every time you call bag.iterator() , you get a new Iterator object, not the same one you had before. 每次调用bag.iterator() ,都会得到一个新的Iterator对象,而不是以前的对象。 You should get the iterator once, then use it through your loop: 您应该获取一次迭代器,然后在循环中使用它:

public boolean remove(T item) {
    Iterator<T> iter = bag.iterator();
    while (iter.hasNext()) {
        T i = iter.next();
            if (i.equals(item)) {
                iter.remove();
                return true;
            }
    }
    return false;
}

Your code has another issue: if you call remove() on your iterator before you call next() , your code will try to access data[-1] . 您的代码还有另一个问题:如果在调用next()之前在迭代器上调用remove() next() ,则代码将尝试访问data[-1] You might want to put some protection code around that such as: 您可能需要在其中添加一些保护代码,例如:

public void remove() {
    if(current > 0) {
        for (int i=current-1; i<size-1; i++)
            data[i] = data[i+1];
        size--;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM