补充一下,我在重写hashcode的时候直接return 0,然后equals方法里面就判断了只要是属性相同就为true
额,抱歉,现在才看到!!/(ㄒoㄒ)/~~
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
System.out.println(this+"----"+obj);
Student student = (Student)obj;
if(this.username.equals(student.username)&&this.age==student.age){
return true;
}else {
return false;
}
}
@Override
public String toString() {
return "Student [username=" + username + ", age=" + age + "]";
}
Student s1 = new Student("Yuengh",22);
Student s2 = new Student("李连贤",22);
Student s3 = new Student("何立松",22);
Student s4 = new Student("Yuengh",22);
Student s5 = new Student("胡凯杰",22);
HashSet hs = new HashSet<>();
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
hs.add(s5);
for(Student st:hs){
System.out.println(st.getUsername()+"----------"+st.getAge());
}
比如说我添加s3的时候,按照我昨天看视频的结果是先会跟s2比较,然后再跟s1比较,但是我刚刚实验的结果是相反的,先跟s1比较,再跟s2比较,我现在很好奇这种顺序是怎么来的?