Iterate through TreeSet in java and update it

I have a TreeSet in Java, and I have my own comparator function for this set of trees. Now I am browsing this tree using the descendingIterator() method and changing the elements. So does this update the actual tree as well as wrt so that it sorts with my custom comparator? Or do I need to delete an item and return the updated item?

+4
source share
3 answers

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

Note that deleting an item during iteration will only work using the iterator removal method. And you will not be able to add it during iteration without having received ConcurrentModificationException, AFAIK. Therefore, save it in the list of elements that will be re-added to the set after the iteration is completed.

+8
source

If you modify any part of the object that is part of the "key" (as defined by your custom comparator), you need to delete and reinsert the object so that the tree is "recognized" about this change. You should not do this during the iteration: a good approach is to collect the elements that need to be changed in one loop, and then modify and reinsert them in another loop.

+3
source

As a general rule, it is not recommended to β€œmodify” any types of values ​​added to Java containers that rely on equality, a hash code, etc., given that none of the known standard containers performs automatic balancing or tuning in response to a change values ​​(which makes sense).

Along with Set this rule is equally true for Map types. If you iterate over the map and change the "key" in place, everything goes wrong. For this reason, it is recommended to use immutable types as the keys of your map (think of String , Integer , etc.). Your example can be demonstrated with a simple example:

 public class Test { public static void main(final String[] args) { Mutable m1 = new Mutable(1); Mutable m2 = new Mutable(2); Mutable m3 = new Mutable(3); Mutable m4 = new Mutable(4); TreeSet<Mutable> ts = new TreeSet<Mutable>(new Cmp()); ts.add(m1); ts.add(m2); ts.add(m3); ts.add(m4); System.out.println(ts); for (Iterator<Mutable> iter = ts.iterator(); iter.hasNext(); ) { Mutable m = iter.next(); if (mi == 1 || mi == 3) { mi = mi + 10; } } System.out.println(ts); } } class Mutable { public int i; public Mutable(int i) { this.i = i; } public String toString() { return "Mutable[" + i + "]"; } } class Cmp implements Comparator<Mutable> { @Override public int compare(Mutable o1, Mutable o2) { return Integer.valueOf(o1.i).compareTo(Integer.valueOf(o2.i)); } } Output: [Mutable[1], Mutable[2], Mutable[3], Mutable[4]] [Mutable[11], Mutable[2], Mutable[13], Mutable[4]] 
+1
source

Source: https://habr.com/ru/post/1388817/


All Articles