Java HashSet collection storage traversal student object code examples


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.

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113917751