I've got a object that defines a 'natural sort order' using Comparable<>. These are being stored in TreeSets.
Other than removing and re-adding the object, is there another way to update the sort when the members that are used to define the sort order are updated?
The TreeSet stores the objects in the ascending order, which is a natural ordering of a tree. We can also specify a comparator to sort the elements based on it during the creation of the TreeSet. It implements the SortedSet and NavigableSet interface to maintain and navigate the order of the elements.
Once you add back the object, the treeset will once again sort it.
The elements in a TreeSet are sorted as per their natural ordering, or based on a custom Comparator that is supplied at the time of creation of the TreeSet. TreeSet cannot contain null value. TreeSet internally uses a TreeMap to store elements.
If null, the natural ordering of the elements will be used. 1. Unique Elements : Since HashSet and TreeSet both implements Set interface . Both are allowed to store only unique elements in their objects.
As others have noted, there is no in-built way. But you can always subclass that TreeSet, with your constructor(s) of choice, and add in the required functionality:
public class UpdateableTreeSet<T extends Updateable> extends TreeSet<T> { // definition of updateable interface Updateable{ void update(Object value); } // constructors here ... // 'update' method; returns false if removal fails or duplicate after update public boolean update(T e, Object value) { if (remove(e)) { e.update(value); return add(e); } else { return false; } } }
From then on, you will have to call ((UpdateableTreeSet)mySet).update(anElement, aValue)
to update the sorting value and the sorting itself. This does require you to implement an additional update()
method in your data object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With