java – 比较时理解TreeSet返回0
我创建了一个这样的Student类:
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 + "]"; } } 这是我的测试类,我只是在我的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); } } 根据我的程序,输出是: [Student [firstName=A1,lastName=A2],Student [firstName=A2,lastName=B2],Student [firstName=B1,lastName=B2]] 在我的测试类中,我将Student对象添加到TreeSet,而且我还没有覆盖hashCode&等于方法.所以我期待TreeSet将保存所有4个对象,但我也可以看到它包含3个对象.你能解释为什么新学生(“A1”,“B2”)不属于我的TreeSet吗? 此外,根据Java docs for TreeSet,它说:
因为我没有覆盖equals方法,那么为什么集合没有所有四个元素? 解决方法
正如
java.util.TreeSet所说:
感谢@Jon Skeet. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |