使用arraylist删除数组中的重复项失败

时间:2013-11-25 05:36:26

标签: java arrays arraylist

我想通过使用数组列表从数组中删除重复项。代码似乎适用于所有情况,除非String []数组包含三个元素副本。为什么会出现这个问题以及如何解决?

Test input - 
array = {"D22", "D22", "D22"};

Output = 
D22
D22

Expected output = 
D22

public static String[] removeDuplicates(String [] array){
    String [] noDups = null;
    ArrayList<String> copy = new ArrayList<String>();
    String first = "";
    String next = "";

    for(String s: array){
        copy.add(s.trim());//Trimming
    }

    for(int i = 0; i < copy.size(); i++){

        for(int j = i + 1; j < copy.size(); j++){

            first = copy.get(i);
            next = copy.get(j);

            if(first.equals(next)){
                copy.remove(j);
            }

        }


    }

    noDups = copy.toArray(new String[copy.size()]);

    for(String s: noDups){
        System.out.println(s);

    }

    return noDups;
}

4 个答案:

答案 0 :(得分:4)

试试这个,它最简单:

public static String[] removeDuplicates(String[] array) {
    ArrayList<String> res = new ArrayList<String>();

    for (String str : array) {
        if (!res.contains(str)) {
            res.add(str);
        }
    }
    return res.toArray(new String[res.size()]);
}

public static void main(String[] args) {
    String[] arr = {"D22", "D22", "D22"};
    String[] res = removeDuplicates(arr);
    for (String string : res) {
        System.out.println(string);
    }
}

输出:D22

答案 1 :(得分:2)

这是因为当你调用remove时,你的计数器也会增加,导致它跳过一个元素。像

这样的东西
if(first.equals(next)){
  copy.remove(j);
  j--;
}

应该解决这个问题

答案 2 :(得分:1)

从数组中删除元素时,每个后续元素都会向左移动一个空格。这会使您有效地跳过元素。示范:

Initial state
Index:   0 1 2
Element: A B C
i: 0
j: 1
A=B, therefore A is removed
Index:   0 1
Element: B C
j: 2 (You increment it regardless of whether an element was removed)
j>=size(), therefore go to outer loop
i: 1
There is nothing after element C, therefore you're done.

答案 3 :(得分:0)

如果仔细查看for循环for(int j = i + 1; j < copy.size(); j++){,每次迭代列表时都会计算copy.size()的值。当您从副本列表中删除值时,大小会减少一个。

您正在迭代以及修改导致问题的相同列表(使用copy.remove(j);)。

对此有几种选择:

  • 使用Set代替List。它会自动删除重复项。
  • 或者当您在副本列表上进行迭代时,请将非重复值添加到其他列表列表中,而不是修改副本列表。