为什么在将Array转换为HashSet后仍然存在重复的元素

时间:2013-10-15 12:36:12

标签: java

我有一个简单的数组:

String[] names = {"apple","apple","orange","orange"};
System.out.println("length is "+ names.length); //length is 4

我尝试在数组中没有那些重复元素的集合,因为Java doc说Set是一个不包含重复元素的集合,因此我使用Set删除重复的元素:< / p>

Set<String> nameSet = new HashSet<String>(Arrays.asList(names));
System.out.println("length is "+ nameSet.size()); //length is 4 still

但是nameSet仍然包含重复的元素,为什么我的Set没有唯一的元素?

如何在不迭代数组的情况下解决我的问题?

1 个答案:

答案 0 :(得分:9)

您必须运行不同的代码

String[] names = {"apple","apple","orange","orange"};
System.out.println("length is "+ names.length); //length is 4

Set<String> nameSet = new HashSet<String>(Arrays.asList(names));
System.out.println("length is "+ nameSet.size()); //length is 2

按预期打印。

length is 4
length is 2