jchitel
jchitel

Reputation: 3169

Java - Reset iterator values in a loop

So I've never known much about how Java iterators/iterables/iterations work, and every once and awhile I'm hesitant on how to do something. This is one of those times.

I have a list of objects, and I need to change each one. But as I have to literally reset each reference in the list, I'm not sure how to do this. I came up with this implementation that would make it absolutely certain to work:

for (Object obj : new ArrayList<Object>(list)) {
    list.remove(obj);
    list.add(change(obj));
}

Note that I cannot just do this:

for (Object obj : list) { change(obj) }

because due to the nature of obj, I cannot modify it in place. Change() returns a new object that is changed.

Basically, I'm asking if this will be ok:

for (Object obj : list) {
    obj = change(obj);
}

or if I have to use the top implementation.

Upvotes: 1

Views: 1426

Answers (3)

Paul Vargas
Paul Vargas

Reputation: 42040

You can do the next:

for (int i = 0; i < list.size(); i++) {
    list.set(i, change(list.get(i)))
}

The javadoc for the method public E set(int index, E element) in java.​util.​List states:

Replaces the element at the specified position in this list with the specified element (optional operation).

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 692023

If you want to avoid making a copy of the list, the best way is to use a ListIterator:

for (ListIterator<Object> it = list.listIterator(); it.hasNext(); ) {
    Object obj = it.next();
    it.set(change(obj));
}

The advantage over the solution that uses get(i) and set(i) is that it's O(n) whatever the type of the list. Accessing elements by index on a LinkedList is very inefficient.

Upvotes: 2

NESPowerGlove
NESPowerGlove

Reputation: 5496

for (Object obj : list) {
    obj = change(obj);
}

Would not work because you are only changing a local variable reference, not the reference that is in the list.

Upvotes: 0

Related Questions