java - My treemap breaks after sorting it because "comparator used for the treemap is inconsistent with equals" -
i needed sort treemap based on it's value. requirements of i'm doing such have use sorted map. tried solution here: sort map<key, value> values (java) comments say, make getting values map not work. so, instead did following:
class sorter implements comparator<string> { map<string, integer> _referencemap; public boolean sortdone = false; public sorter(map<string, integer> referencemap) { _referencemap = referencemap; } public int compare(string a, string b) { return sortdone ? a.compareto(b) : _referencemap.get(a) >= _referencemap.get(b) ? -1 : 1; } }
so leave sortdone false until i'm finished sorting map, , switch sortdone true compares things normal. problem is, still cannot items map. when mymap.get(/anything/) null still.
i not understand comparator inconsistent equals means.
i not understand comparator inconsistent equals means.
as per contract of comparable interface.
the natural ordering class c said consistent equals if , if e1.compareto(e2) == 0 has same boolean value e1.equals(e2) every e1 , e2 of class c. note null not instance of class, , e.compareto(null) should throw nullpointerexception though e.equals(null) returns false.
it recommended (though not required) natural orderings consistent equals.
i believe need change line :
_referencemap.get(a) >= _referencemap.get(b) ? -1 : 1;
to
_referencemap.get(a).compareto(_referencemap.get(b));
since if integer
returned _referencemap.get(a)
==
in value integer
returned _referencemap.get(b)
should ideally return 0
, not -1
.
Comments
Post a Comment