I wanted to remove duplicates from an array, by using an array list. The code seems to work fine for all cases except when String[]array contains three copies of an element. Why does this problem happen and how to fix 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;
}