w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
My treemap breaks after sorting it because "comparator used for the treemap is inconsistent with equals"

I also do not understand what the comparator inconsistent with equals even means.

As per the contract of the Comparable interface.

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

It is strongly recommended (though not required) that natural orderings be consistent with equals.

I believe you need to change the line :

 _referenceMap.get(a) >= _referenceMap.get(b) ? -1 : 1;



Since if the Integer returned by _referenceMap.get(a) is actually == in value to the Integer returned by _referenceMap.get(b) then you should ideally return 0, not -1.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.