Java – understanding TreeSet returns 0 during comparison
•
Java
I 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. 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); } }
According to 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 added the student object to TreeSet, and I haven't overridden the hashcode & equals method So I expect TreeSet to save all four objects, but I can also see that it contains three objects Can you explain why new students ("A1", "B2") do not belong to my TreeSet?
In addition, according to Java docs for TreeSet, it says:
Because I didn't override the equals method, why didn't the collection have all four elements?
Solution
Just like Java util. TreeSet said:
Thank you @ Jon skeet
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码