How TreeSet checks for Duplicates

后端 未结 3 782
感情败类
感情败类 2021-02-10 18:06

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:42

    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.

提交回复
热议问题