我有一个简单的数组:
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没有唯一的元素?
如何在不迭代数组的情况下解决我的问题?
答案 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