Thursday 19 February 2015

What does comparison being consistent with equals mean ? What can possibly happen if my class doesn't follow this principle?

The contract of the Comparable interface allows for non-consistent behaviour:
It is strongly recommended (though not required) that natural orderings be consistent with equals.
So in theory, it is possible that a class in the JDK had a compareTo not consistent with equals. One good example is BigDecimal.
Below is a contrived example of a comparator that is not consistent with equals (it basically says that all strings are equal).
Output:
size: 1
content: {a=b}
public static void main(String[] args) {
    Map<String, String> brokenMap = new TreeMap<String, String> (new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return 0;
        }
    });

    brokenMap.put("a", "a");
    brokenMap.put("b", "b");
    System.out.println("size: " + brokenMap.size());
    System.out.println("content: " + brokenMap);
}

but see now if you store same entry in hashmap
it will store because a.equals(b) always false. so it will store both a and b.
where as in TreeMap it wont thats the problem. because compare b/w a and b is 0...so
 1 will broke single value will store

No comments:

Post a Comment