Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Compare/sort arbitrary objects

Is there anyway I can define a sequence/order for all objects in a JVM so that for any two distinct objects o1 or o2, there's a well defined rule that says either o1 > o2 or o2 > o1 and o1 == o2 if and only if they are the same object?

identityHashCode() comparison would be a good candidate, if there's a no-collision guarantee (there isn't).

Birth time would work too - if I can somehow obtain that.

Any ideas?

Thank you!

like image 350
RAY Avatar asked Apr 11 '11 07:04

RAY


People also ask

How to sort a comparable object in Java?

A Comparable object is capable of comparing itself with another object by natural ordering. The class must implement the java.lang.Comparable interface to compare its instances. Using Comparable interface we can sort: Where T is the type of Object to be sorted.

Is it possible to sort a list using collections in Java?

Above example worked perfectly with Collections.Sort () as List defined in example was Lits<String> and java.lang.String implements the Comparable interface. With List contains custom objects, Collections.sort () will fail if the custom object does not implement the Comparable interface.

How to sort a class by its instance in Java?

The class must implement the java.lang.Comparable interface to compare its instances. Using Comparable interface we can sort: Where T is the type of Object to be sorted.

How to sort an ArrayList in Java?

1. Sort an ArrayList Collections API’s utility class Collections provide a handy way to sort an ArrayList in a natural ordering provided all elements in the list must implement the Comparable interface.


1 Answers

If you are in a position to maintain your own repository of objects, you could use a WeakHashMap<Object, Long> to maintain your own serial IDs.

like image 166
Jim Blackler Avatar answered Sep 28 '22 02:09

Jim Blackler