Failed to delete duplicates in array using ArrayList

I want to remove duplicates from the array by using the array list The code seems to work in all cases unless the string [] array contains three copies of elements Why does this problem occur and how to solve it?

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

Solution

This is because when you call remove, your counter will also increase, causing it to skip an element It's like

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

This problem should be solved

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>