Jan Kaufmann Jan Kaufmann - 1 year ago 80
Java Question

Does Comparator work differently with wrapper class?

I keep failing sorting student IDs from the database , after long time figuring it out as to why it gets sorted incorrectly, I concluded that this Comparator works differently with the Wrapper Class ?

public class comparatorDemo {
public static void main(String[] args) {
Comparator<Integer> IDComparator = new Comparator<Integer>() {
public int compare(Integer firstID, Integer secondID) {
return firstID < secondID ? (-1) : (firstID == secondID ? (0) : (1));

System.out.println(IDComparator.compare(new Integer(1), new Integer(1))); // prints 1
System.out.println(IDComparator.compare((1),(1))); // prints 0
} }

What is going on here ?

Answer Source

In Java, when using == to compare two references, the result will be true if and only if the two references point to the same exact object. So when you are comparing new Integer(1) with new Integer(1), == will return false

When using == to compare to primitives (like int) then true will be returned when the values are equal.

One solution is to use firstID.equals(secondID)

Check out this for more information


As mentioned by JBNizet, you can replace

return firstID < secondID ? (-1) : (firstID == secondID ? (0) : (1));


return firstID.compareTo(secondID);

which makes the code a lot easier to read and of course uses the correct comparison.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download