-6

我有一个简单的数组:

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

我尝试在数组中创建一个没有那些重复元素的集合,因为 Java 文档说Set是一个不包含重复元素的集合,所以我Set用来删除重复的元素:

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

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

以及如何在不遍历数组的情况下解决我的问题?

4

1 回答 1

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
于 2013-10-15T12:39:03.667 回答