Since the Set collection does not store duplicate elements, what will happen if I add a duplicate element normally when doing this case?
public class HashSetDemo {
public static void main(String[] args) {
//创建HashSet集合对象
HashSet<Student> hashSet = new HashSet<Student>();
//创建学生对象
Student s1 = new Student("爱学习", 21);
Student s2 = new Student("爱Java", 22);
Student s3 = new Student("坚持不懈", 23);
Student s4 = new Student("爱Java", 22);
//把学生添加到集合
hashSet.add(s1);
hashSet.add(s2);
hashSet.add(s3);
hashSet.add(s4);
//遍历集合(增强for循环)
for (Student s : hashSet) {
System.out.println(s.getName() + "," + s.getAge());
}
}
}
operation result:
Through the results of the operation, we found that the repeated elements are still added. What is the reason? According to the source code analysis and the underlying data structure of HashSet, it can be known that if two objects have the same hash value (hashCode method) and the content of the object is also the same (equals method), they will not be stored in the hash table. So we need to rewrite the hashCode method and equals method in the stored object class to solve the problem of adding duplicate elements.
After rewriting the hashCode method and equals method in the object class (automatically generated), run the above code and run the result:
It can be seen that the repeated elements are not added to the collection.