Reputation: 1059
I am multiple ArrayLists with custom objects that implement the Comparatorinterface. Its possible that these multiple lists have the same objects. My requirement is each list can have its own order
For eg:
list 1 can contain 4 objects Obj2, Obj4, Obj1, Obj3 list 2 can contain say 5 objects Obj4, Obj3 , Obj5 , Obj1 , Obj2
If I assign an id of (0,1,2,3,4) in List1 to each custom object and use the sort method on the ArrayList I think it will work for me if I have a single List.
But I cannot do that because the same objects will need to be in different order for List2. Is there a way I can use the comparator and depend on the Collections framework sorting for me instead of me having to maintain a separate order list for each ArrayList ?
Any help will be greatly appreciated.
Thanks
Upvotes: 0
Views: 439
Reputation: 8874
In order to preserve the lists in different orders, you need to have copies of this list. If you just keep multiple reference to one list, then sorting on one reference will affect other references too.
Don't worry about having multiple copies of one list. The lists themselves also have the content as a reference. So if you make a new List from another list, you will create a copy of the list, but not copies of the elements in the list. They are kept as a reference in the list and won't be affected in any way.
Upvotes: 0
Reputation: 2674
either use a custom written comparator impl:
Collections.sort(list, new Comparator<Comparable<?>>() {
@Override
public int compare(final Comparable o1, final Comparable o2) {
// Compare two objects, might not be the same type
}
});
OR, preferably, have all of the classes being compared to each other implement a common interface CustomComparableIntf
and then implement Comparable<CustomComparableIntf>
so they are being compared as implementations of that interface, rather than their concrete type.
Upvotes: 0
Reputation: 2854
Write a custom comparator, then use Collections.sort(list, comparator). You can have two (or how ever many you need) comparators to allow you to sort your objects based on different parameters.
Upvotes: 1