问题描述
考虑以下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.
为方法
Set
javadoc for the equals(Object)
method
LinkedHashSet
javadoc状态
The LinkedHashSet
javadoc states
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()具有相同的元素但顺序不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!