Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

maintaining TreeSet sort as object changes value

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?

like image 789
Stevko Avatar asked Apr 05 '10 17:04

Stevko


People also ask

How TreeSet can maintain sorting of objects?

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.

Does TreeSet automatically sort in Java?

Once you add back the object, the treeset will once again sort it.

Is a TreeSet automatically sorted?

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.

Does TreeSet store unique values?

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.


1 Answers

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.

like image 153
tucuxi Avatar answered Oct 20 '22 05:10

tucuxi