...

/

Solution Review: Remove Duplicates From an ArrayList

Solution Review: Remove Duplicates From an ArrayList

In this review, solution of the challenge 'Remove Duplicates From an ArrayList' from the previous lesson is provided.

We'll cover the following...

Solution

Java
class DuplicatesRemover {
public static void removeDuplicates(ArrayList < Character > arrList) {
for (int i = 0; i < arrList.size(); i++) {
for (int j = i + 1; j < arrList.size(); j++) {
if (arrList.get(i).equals(arrList.get(j))) { //check if there is any duplicate
arrList.remove(j); //remove duplicate
j--; // j is decremented
}
}
}
}
public static void main( String args[] ) {
ArrayList<Character> input = new ArrayList<Character>(Arrays.asList('d', 'c','a', 'b', 'b', 'c', 'c', 'c', 'd'));
System.out.println("Array List before calling removeDuplicates");
for (int i = 0; i < input.size(); i++){
System.out.print(input.get(i)+ " ");
}
System.out.println();
removeDuplicates(input);
System.out.println("Array List after calling removeDuplicates");
for (int i = 0; i < input.size(); i++){
System.out.print(input.get(i)+ " ");
}
System.out.println();
}
}

How does the above code work?

  • In the above solution code, we ...