Understanding TreeSet when compareto returns 0

learner picture learner · Jul 10, 2015 · Viewed 9k times · Source

I have created a Student class like this:

public class Student implements Comparable<Student> {

    private String firstName;
    private String lastName;

    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    // Getters & Setters follow here...

    @Override
    public int compareTo(Student student) {
        int hash = this.firstName.compareTo(student.firstName);
        return hash;
    }

    @Override
    public String toString() {
        return "Student [firstName=" + firstName + ", lastName=" + lastName
                + "]";
    }

}

This is my test class where I just add elements to my TreeSet:

public class SortedSetExample1 {
    public static void main(String[] args) {
        SortedSet<Student> set = new TreeSet<Student>();
        set.add(new Student("A1","A2"));
        set.add(new Student("B1","B2"));
        set.add(new Student("A1","B2"));
        set.add(new Student("A2","B2"));
        System.out.println(set);
    }
}

As per my program the output is:

[Student [firstName=A1, lastName=A2], Student [firstName=A2, lastName=B2], Student [firstName=B1, lastName=B2]]

In my test class I am adding Student objects to TreeSet, and also I have not overridden the hashCode & equals methods. So I was expecting that the TreeSet will hold all the 4 objects but I can also see that it contains 3 objects. Can you please explain why new Student("A1","B2") is not part of my TreeSet?

Also as per the Java docs for TreeSet here, it says:

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

As I have not overridden the equals method then why the collection is not having all the four elements?

Answer

meskobalazs picture meskobalazs · Jul 10, 2015

As java.util.TreeSet says:

a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal

Kudos to @Jon Skeet.