0

在将它添加到arraylist 之前,我必须在arraylist 中找到任何重复的元素。但它没有给出正确的输出。编译和运行都不会出现任何错误。

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);
            }
        }
    }
}
4

1 回答 1

3

虽然 java.util.ArrayList.add()确实返回一个布尔值,但它被硬编码为始终为真。

您似乎已经假设如果元素已经在列表中,它将返回 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);
        }
    }
}

您也可以考虑使用 aSet<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);
        }
    }
}

笔记

有关始终返回 true 的详细信息,请参阅 javadoc on ArrayList.add()

于 2013-11-02T11:03:43.993 回答