Skip to content
Advertisement

Tag: comparable

compareTo: treat two nulls as equal

I would like my compare method to work so that in the case where field1 == null in both objects, comparation would not be determined, but field2 would be checked, and so on. How to do it in the simplest way? The method below does not work well: when the fields from both objects are null, the comparison is always

Why compareTo throws NPE using a comparator who doesn’t do that when user separatedly

I created a comparator that never throws NPE. However, when using it inside compareTo, it throws NPE. Why? When expliciting the comparator on Collections.sort call, sort operation doesn’t use compareTo implementation, as expected. When not doing this, sort operation uses the implementation of compareTo. Since this method calls the exact same comparator, why do I get NPE here? I mean,

java.lang.Comparable and equals

If I implement java.lang.Comparable for a class, do I still have to override the equals() method? Or will the Comparable work for equals as well? If the answer is no, then what if some discrepancy arises? Let’s say the way I term two objects as equal within the equals() method is different from the way I term two objects of

Advertisement