Deep compare sets in Java

后端 未结 2 1259
不知归路
不知归路 2021-01-11 17:22

I have two sets in Java that compare Item objects. Is there a method to compare the sets so that Item\'s equals method is invoked and

2条回答
  •  粉色の甜心
    2021-01-11 18:20

    Each child of AbstractSet does that. See the docs

    public boolean equals(Object o)

    Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface. This implementation first checks if the specified object is this set; if so it returns true. Then, it checks if the specified object is a set whose size is identical to the size of this set; if not, it returns false. If so, it returns containsAll((Collection) o).

    So in fact this relies on the contains implementation (which is invoked by containsAll(..)). For HashSet (at least) this is what you are looking for.

提交回复
热议问题