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

﹥>﹥吖頭↗ 提交于 2019-12-01 04:19:25

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.

As mentioned above: LinkedHashSet extends HashSet which extends AbstractSet which implements equals method: https://docs.oracle.com/javase/8/docs/api/java/util/AbstractSet.html#equals-java.lang.Object-

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.

The easiest way to compare LinkedHashSet if order if important to you is to serialize it and compare them then:

    LinkedHashSet<Integer> reverseOrder = new LinkedHashSet<>();
    reverseOrder.add(2);
    reverseOrder.add(1);
    LinkedHashSet<Integer> ordered = new LinkedHashSet<>();
    ordered.add(1);
    ordered.add(2);
    System.out.println("Equals via set: " + ordered.equals(reverseOrder));
    System.out.println("Equals With Arrays: " + ordered.ordered.toString().equals(reverseOrder.ordered.toString()));

Result:

Equals via Set: true
Equals With Arrays: false
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!