How TreeSet checks for duplicates

I check how TreeSet checks for duplicate elements and has the following code

  import java.util.*;

  public class TreeDemo{

    public static void main(String[] args)
        {
            new TreeDemo().go();
        }

    public void go()
    {
        Song s1 = new Song("song1","artist1");
        Song s2 = new Song("song2","artist2");
        Song s3 = new Song("song3","artist3");
        Song s4 = new Song("song3","artist3");

        Set<Song> tree = new TreeSet<Song>();

        tree.add(s1);
        tree.add(s2);
        tree.add(s3);
        tree.add(s4);

        System.out.println(tree);

    }
}

class Song implements Comparable<Song>{
    private String title;
    private String artist;

    public Song(String t, String a)
    {
        title=t;
        artist=a;
    }

    public String getTitle(){
        return title; 
    }

    public int compareTo(Song s){
        //Song s = (Song)o;
        return title.compareTo(s.getTitle());
    }

public String toString(){
    return title;
}

}

When I execute this code, I get the following output

[song1, song2, song3]

My question is: -

  • Even if I did not implement the hashCode and equals method (I implemented the Comparable interface from the time it was required and needed to sort the Set), how did the TreeSet identify duplicates?
  • Did he use the default implementation of the Object class? It looks like he used the "title" field for this check, because when I add it treats it as a duplicate, but when I add it, it does not treat it as a duplicate.

Thank.

+3
source share
3 answers

TreeSet ( , TreeMap, ) compareTo() . Object .equals() .hashCode(). , ,

[song1, song2, song3, song3]

Object , .

+5

< 0, 0 > 0... , equals compareTo, 0. ,

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

node

+1
+1

All Articles