I\'ve always loved trees, that nice O(n*log(n))
and the tidiness of them. However, every software engineer I\'ve ever known has asked me pointedly why I would u
Even after 11 years, nobody thought of mentioning a very important difference.
Do you think that if HashSet
equals TreeSet
then the opposite is true as well? Take a look at this code:
TreeSet treeSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
HashSet hashSet = new HashSet<>();
treeSet.add("a");
hashSet.add("A");
System.out.println(hashSet.equals(treeSet));
System.out.println(treeSet.equals(hashSet));
Try to guess the output and then hover below snippet for seeing what the real output is. Ready? Here you go:
false
true
That's right, they don't hold equivalence relation for a comparator that is inconsistent with equals. The reason for this is that a TreeSet
uses a comparator to determine the equivalence while HashSet
uses equals
. Internally they use HashMap
and TreeMap
so you should expect this behavior with the mentioned Map
s as well.
Originally answered