How TreeSet checks for Duplicates

后端 未结 3 486
耶瑟儿~
耶瑟儿~ 2021-02-10 18:02

I am checking how TreeSet checks for duplicate elements and have the following code

  import java.util.*;

  public class TreeDemo{

    public static void main(         


        
相关标签:
3条回答
  • 2021-02-10 18:17

    a comparator return < 0, 0 or > 0... So equals is implemented by compareTo returning 0. Thus

    if (node1.compareTo(node2) == 0) 
    

    then the node is already in the set

    0 讨论(0)
  • 2021-02-10 18:22

    TreeSet implements a balanced binary search tree based upon ordering of its members (via the Comparable or Comparator interfaces), not on hashing.

    http://en.wikipedia.org/wiki/Self-balancing_binary_search_tree

    0 讨论(0)
  • 2021-02-10 18:25

    TreeSet (or technically, the TreeMap that backs it) only uses the compareTo() function to compare the elements. It does not use Object's .equals() or .hashCode(). Moreover, if it had used any of them, your output would have been

    [song1, song2, song3, song3]
    

    because Object's default implementation uses memory addresses to test object equality, not their members.

    0 讨论(0)
提交回复
热议问题