How to iterate over a SortedSet to modify items within

nKognito picture nKognito · Nov 29, 2011 · Viewed 13.4k times · Source

lets say I have an List. There is no problem to modify list's item in for loop:

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

But I have a SortedSet instead of list. How can I do the same with it? Thank you

Answer

NPE picture NPE · Nov 29, 2011

First of all, Set assumes that its elements are immutable (actually, mutable elements are permitted, but they must adhere to a very specific contract, which I doubt your class does).

This means that generally you can't modify a set element in-place like you're doing with the list.

The two basic operations that a Set supports are the addition and removal of elements. A modification can be thought of as a removal of the old element followed by the addition of the new one:

  1. You can take care of the removals while you're iterating, by using Iterator.remove();
  2. You could accumulate the additions in a separate container and call Set.addAll() at the end.