rockandride
rockandride

Reputation: 41

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. 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:

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

Upvotes: 0

Views: 199

Answers (1)

Jason
Jason

Reputation: 11832

Every time you call bag.iterator(), you get a new Iterator object, not the same one you had before. 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]. 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--;
    }
}

Upvotes: 3

Related Questions