LinkedHashSet .equals()vs LinkedList .equals()具有相同的元素但顺序不同 [英] LinkedHashSet .equals() vs LinkedList .equals() with same elements but different order
问题描述
考虑以下SSCCE:
public static void main(String[] args) {
LinkedHashSet<String> set1 = new LinkedHashSet<>();
set1.add("Bob");
set1.add("Tom");
set1.add("Sam");
LinkedHashSet<String> set2 = new LinkedHashSet<>();
set2.add("Sam");
set2.add("Bob");
set2.add("Tom");
System.out.println(set1);
System.out.println(set2);
System.out.println(set1.equals(set2));
}
打印:
[Bob, Tom, Sam]
[Sam, Bob, Tom]
true
但是如果你将 LinkedHashSet
更改为 LinkedList
:
public static void main(String[] args) {
LinkedList<String> set1 = new LinkedList<>();
set1.add("Bob");
set1.add("Tom");
set1.add("Sam");
LinkedList<String> set2 = new LinkedList<>();
set2.add("Sam");
set2.add("Bob");
set2.add("Tom");
System.out.println(set1);
System.out.println(set2);
System.out.println(set1.equals(set2));
}
它产生:
[Bob, Tom, Sam]
[Sam, Bob, Tom]
false
我的问题是澄清。有人可以帮助理解这个吗?为什么 LinkedHashSet
被视为等于,而相同的 LinkedList
不会?我假设 List
的定义和 Set
扮演一个角色,但我不确定。
My question is one of clarification. Can someone help make sense of this? Why would a LinkedHashSet
be considered equals whereas the same LinkedList
would not? I'm assuming the definition of List
and Set
plays a role, but I'm not sure.
基本上,我说如果你认为 Set
是相同的,你不会考虑列表
s也一样吗?反之亦然(假设没有重复的元素)?
Basically, I'm saying if you consider the Set
s to be the same, wouldn't you consider the List
s to be the same too? And vice-versa (assuming no duplicate elements)?
推荐答案
保证 LinkedHashSet
make是关于迭代顺序的。但是,它仍然是 Set
,而且一套不关心订单本身。另一方面,列表
。一个元素位于第三位的 List
与另一个 List
不同,第一个位置的元素相同。
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.
为 javadoc /docs/api/java/util/Set.html#equals%28java.lang.Object%29>
equals(Object)
方法
Set
javadoc for the equals(Object)
method
如果指定的对象也是一个集合,则返回true,两个集合具有相同大小的
,以及指定的每个成员set包含在
这个集合中(或者等价地,这个集合的每个成员都包含在指定集合的
中)。 此定义确保equals方法
在set接口的不同实现中正常工作。
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.
LinkedHashSet
javadoc状态
The LinkedHashSet
javadoc states
Set接口的哈希表和链表实现,
可预测的迭代顺序。
Hash table and linked list implementation of the Set interface, with predictable iteration order.
A LinkedHashSet
是一个集
。它有相同的规则,即。适用于ADT的那些。
A LinkedHashSet
is a Set
. It has the same rules, ie. those that apply to the set ADT.
这篇关于LinkedHashSet .equals()vs LinkedList .equals()具有相同的元素但顺序不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!