在将其添加到数组列表之前,我必须找到数组列表中的任何重复元素。但它没有给出正确的输出。编译和运行都没有报错。
public class MyDuplicateEntry {
public static void main(String a[]) {
String[] strArr = {"one", "two", "three", "four", "four", "five"};
ArrayList<String> unique = new ArrayList<String>();
for (String str : strArr) {
if (!unique.add(str)) {
System.out.println("Duplicate Entry is: " + str);
}
}
}
}
最佳答案
同时java.util.ArrayList.add()
确实返回一个 boolean 值,这被硬编码为始终为真。
您似乎假设如果该元素已在列表中,它将返回 false - 事实并非如此。
您必须手动检查,请参阅 ArrayList.contains()
.
public static void main(String a[]) {
String[] strArr = { "one", "two", "three", "four", "four", "five" };
ArrayList<String> unique = new ArrayList<String>();
for (String str : strArr) {
if (unique.contains(str)) {
System.out.println("Duplicate Entry is: " + str);
} else {
unique.add(str);
}
}
}
您也可以考虑使用Set<String>
相反,因为它们针对检查 contains()
进行了优化- 我建议一个简单的 HashSet<String>
.
这不仅是优化的,而且意味着您可以检查 add 的返回代码,因为如果元素已经在集合中,这将返回 false:
public static void main(String a[]) {
String[] strArr = { "one", "two", "three", "four", "four", "five" };
HashSet<String> unique = new HashSet<String>();
for (String str : strArr) {
if (! unique.add(str)) {
System.out.println("Duplicate Entry is: " + str);
}
}
}
注释
请参阅 ArrayList.add()
上的 javadoc有关始终返回 true 的详细信息。
关于java - 程序未给出预期在 ArrayList 中找到重复项的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19741179/