我担心的是集合的集合 (HashSet s) 是否也检查项目的顺序。 我写了一个应用程序来检查给定的整数集是否存在于整数集中
不知何故,昨天在一台计算机上我注意到整数集是无序的(HashSets 有什么问题)但我担心并写了一些简单的 main 来检查它:
public static void main(String[] args) {
Set<Set<Integer>> set1 = new HashSet<Set<Integer>>();
Set<Integer> set2 = new HashSet<Integer>();
Set<Integer> set3 = new HashSet<Integer>();
set3.add(14); set3.add(2); set3.add(9); set3.add(3); set3.add(5);
set1.add(set3);
set3 = new HashSet<Integer>();
set3.add(6); set3.add(7); set3.add(8); set3.add(9); set3.add(10);
set1.add(set3);
set2.add(9); set2.add(14); set2.add(5); set2.add(2); set2.add(3);
System.out.println(set1);
System.out.println(set2);
if(set1.contains(set2)){
System.out.println(":)");
}else
System.out.println(":(");
}
问题是我看到在这台机器上 HashSet 被订购了什么。输出是:
[[2, 3, 5, 9, 14], [6, 7, 8, 9, 10]]
[2, 3, 5, 9, 14]
:)
所以我的问题是如何比较集合?卜值(value)观而已? (抱歉,如果这个问题听起来很愚蠢。)
最佳答案
So my question is how Sets Compared? Bu values only?
是的,比较两个 Set
时忽略顺序。 Set#equals()
的 JavaDoc 中对此进行了说明:
Compares the specified object with this set for equality. 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.
关于java - Set Of Sets on contain 方法是否检查顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12939701/