一,集合存储元素不重复原理
HashSet集合对象在调用add方法时,会调用元素的hashCode()方法和equals()方法,两方法返回值一致时判定为重复元素。
二,HashSet集合存储自定义元素
set集合保证元素唯一:
存储的元素(String,Integer…Student,Person…),必须重写hashCode()方法和equals()方法。
重写的方法如下:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public class DemoHashSetSaveStudent {
public static void main(String[] args) {
HashSet<Student> set = new HashSet<>();
Student s1 = new Student("小军",18);
Student s2 = new Student("小军",18);
Student s3 = new Student("小红", 19);
set.add(s1);
set.add(s2);
set.add(s3);
System.out.println(set);
//[Student{name='小军', age=18}, Student{name='小红', age=19}, Student{name='小军', age=18}]
//[Student{name='小军', age=18}, Student{name='小红', age=19}]
System.out.println(s1.hashCode());//1967205423|23296487
System.out.println(s2.hashCode());//42121758 |23296487
System.out.println(s1 == s2); //false | false
System.out.println(s1.equals(s2)); //false | true
System.out.println(s3.hashCode());//20671747 | 23653825
}
}