I understand that in Java a Collection<E>
should not be modified while iterating through it, such as removing or adding elements. But what about changing the elements in a List? For example, what if we have
List<String> letters = new ArrayList<String>();
letters.add("A");
letters.add("B");
letters.add("C");
int i = 0;
for (String letter : letters) {
letters.set(i, "D");
i++;
}
So, I'm not talking about modifying the object stored at an element; I'm talking about changing what the object is. The size of the List is not being changed, but the object at the index is changing, so technically the List is being modified. My boss claims this code is fine (and it does appear to work), but I still don't think it is correct. Would a different way of doing it, maybe using the set(E e) method of a ListIterator, be better?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…