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!
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.
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.
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.
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.
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.
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