【发布时间】:2015-03-31 18:59:37
【问题描述】:
似乎在 HashSet 中允许重复。为什么会这样,我该如何删除它们,为什么第二个remove() 不能在下面工作?删除所有重复项的一种方法是new HashSet<>(set),但有没有更好的方法不涉及创建新对象?
Set<ArrayList<String>> set = new HashSet<>();
ArrayList<String> a1 = new ArrayList<>();
ArrayList<String> a2 = new ArrayList<>();
a1.add("a");
set.add(a1);
a1.remove("a");
set.add(a2);
System.out.println(set.size());
System.out.println(set);
ArrayList<String> a3 = new ArrayList<>();
for (Object o : set) {
boolean b = o.equals(a3) && (o.hashCode() == a3.hashCode());
if (!b) System.out.println(false);
}
set.remove(new ArrayList<String>());
System.out.println(set);
set.remove(new ArrayList<String>());
System.out.println(set);
set.remove(set.iterator().next());
System.out.println(set);
System.out.println(set.iterator().next() == a1);
输出:set 由两个相等的空列表组成,而最初不为空的列表无法删除。
2
[[], []]
[[]]
[[]]
[[]]
true
【问题讨论】:
-
或者“不可变类的用处”...
标签: java duplicates hashset duplicate-removal