Hashset vs Treeset

后端 未结 14 1907
再見小時候
再見小時候 2020-11-22 13:38

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

14条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 14:14

    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 Maps as well.

    Originally answered

提交回复
热议问题