Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a TreeSet in java and updating it

Tags:

java

I have a TreeSet in Java and I have my own comparator function for this tree set. Now I am traversing this tree set using descendingIterator() method and changing the elements. So does this update the actual tree set as well wrt to the way it is sorted with my custom comparator? Or do I need to remove the element and put back the updated element?

like image 328
lancelot Avatar asked Dec 12 '22 06:12

lancelot


1 Answers

You need to remove the element and add it back. The position of the element in the tree is decided when the element is inserted, by comparing it with other elements. If you change the object so that the comparison to other elements changes, you must remove the element first, then change it, then re-add it.

Note that removing the element while iterating will only work using the iterator's remove method. And you won't be able to add it during the iteration without getting a ConcurrentModificationException, AFAIK. So store it in a list of elements to be re-added to the set once the iteration has ended.

like image 101
JB Nizet Avatar answered Dec 14 '22 20:12

JB Nizet