Reputation: 450
Is there any built-in collection where object are sorted in sorted order?? and upon changing stored object's field(which is used for determining order), the collection rearranges it self to sorted order.
Underlying objects of the collection are mutable.
Please refer below example.
Emp implements Comparable<Emp> {
Integer id;
Emp(int id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public int compareTo(Emp o) {
return this.id.compareTo(o.id);
}
}
Emp e1 = new emp(1);
Emp e2 = new emp(2);
Emp e3 = new emp(3);
Set<Emp> sortedSet = new TreeSet<Emp>();
sortedSet.add(e1);
sortedSet.add(e2);
sortedSet.add(e3);
// till now object is in sorted order
e2.setId(10);
// I need some method of the collection to make it sorted again.
I need the sortedSet to be again in sorted order(by calling some method) and the order to be e1,e3,e2 after the changes in e2.
If no built-in class is available, give some hint for solving the problem efficiently with minimal time-complexity.
Upvotes: 1
Views: 3083
Reputation: 1
You can remove the object from the set, modify its value, and then add it back to the set once the field value is changed. Once you add back the object, the treeset will once again sort it. This is the best I can think of in this use case.
Upvotes: -1
Reputation: 37655
Almost all of the standard implementations of Set
won't work if you mutate elements in a way that changes their fields. For example, HashSet
uses hashCode
to place entries in buckets, so if you mutate an element after putting it in the Set
, it will no longer be possible to find it. Similarly, a TreeSet
uses a Comparator
(usually using on the elements' fields) to place the elements in a tree, so you'll get similar problems.
So what you are trying to do won't work. What you could do is use an ArrayList
to store the elements and simply sort the List
whenever you need the order. Of course, that will not keep the elements in order at all times. However, that's not possible anyway because collections are not notified of changes to their elements.
Upvotes: 1
Reputation: 46445
No such collection exists. But you can use the Observer pattern to automatically remove/replace the object in the collection when it changes. It is best to remove it before the update happens, and replace it afterwards.
Upvotes: 4
Reputation: 223123
No, you can't just mutate the key in a map or set; that would break future lookups in the map/set.
You should use an immutable sorting key for the map, and when updating your objects, remove the item from the map first, then put it back into the map afterwards with the updated sorting key.
Upvotes: 3