LinkedHashSet .equals() vs LinkedList .equals() with same elements but different order

前端 未结 2 1279
我在风中等你
我在风中等你 2021-01-12 01:50

Consider the following SSCCE:

public static void main(String[] args) {
    LinkedHashSet set1 = new LinkedHashSet<>();
    set1.add(\"Bob         


        
2条回答
  •  别那么骄傲
    2021-01-12 02:39

    The guarantee that LinkedHashSet makes is about iteration order. However, it's still a Set and a set doesn't care about order in itself. A List on the other hand, does. A List with an element in 3rd position is not the same as another List with the same element in the 1st position.

    Set javadoc for the equals(Object) method

    Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

    The LinkedHashSet javadoc states

    Hash table and linked list implementation of the Set interface, with predictable iteration order.

    A LinkedHashSet is a Set. It has the same rules, ie. those that apply to the set ADT.

提交回复
热议问题