HashSet contains problem with custom objects

前端 未结 4 1108
旧时难觅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:41

    HashSet implements Set. The ApiDoc specifies:

    Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set.

    In your example this is the case, because changing name or age on p1 affects equal-comparison. So according the ApiDoc, the behavior of Set in your case is unspecified.

提交回复
热议问题