HashSet contains problem with custom objects

前端 未结 4 1115
旧时难觅i
旧时难觅i 2020-12-05 11:06

My Custom class that will be contained by HashSet

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this         


        
4条回答
  •  天涯浪人
    2020-12-05 11:39

    Because p1.hashCode() changes when you modify p1, so it can't be found at its original index in the hash table anymore. Never let a hash value depend on a mutable field.

    (You're quite lucky that it fails during testing; it might just as well have succeeded, only to fail in production.)

提交回复
热议问题