Brainteaser: Broken comparator
Question: The following program returns result "1", which indicates that first Integer value is greater than the second, why?
In this case, comparator for natural order on Integer is written for example only, and in practice there is no need to write it.
Looking forward for your answers dear readers
Resources:
Effective Java
If you like this post, then consider subscribing to the full feed RSS.
import java.util.*;Please note:
public class Example {
public static void main(String[] args) {
System.out.println("Result: " +
naturalOrder.compare(new Integer(90),
new Integer(90)));
}
private static Comparator<Integer> naturalOrder =
new Comparator<Integer>() {
public int compare(Integer first, Integer second) {
return first < second ? -1 : (first == second ? 0 :1);
}
};
}
In this case, comparator for natural order on Integer is written for example only, and in practice there is no need to write it.
Looking forward for your answers dear readers
Resources:
Effective Java
Related Posts
Brainteaser Drools: Testing Objects
Brainteaser: Broken case of inheritance
Brainteaser: Overridable methods
Java and those frameworks
Brainteaser: ArrayList VS TreeSet
How to set SecurityManager and Java security policy programmatically
Hack any Java class using reflection attack
Singleton pattern and problem with double checked locking
If you like this post, then consider subscribing to the full feed RSS.
















