...

/

Solution Review: Removing Duplicates From an ArrayList

Solution Review: Removing Duplicates From an ArrayList

The solution to the 'Removing Duplicates From an ArrayList' challenge.

Rubric criteria

Solution

Press + to interact
import java.util.ArrayList;
class Duplicates
{
public static void main(String args[])
{
ArrayList<String> colours = new ArrayList<String>();
// Adding the values
colours.add("blue");
colours.add("blue");
colours.add("red");
colours.add("yellow");
colours.add("green");
colours.add("red");
colours.add("red");
colours.add("green");
colours.add("blue");
// Calling the function removeDuplicates
removeDuplicates(colours);
System.out.println(colours);
}
// Implementing removeDuplicates function
public static void removeDuplicates(ArrayList<String> colours)
{
for(int i = 0; i < colours.size()-1; i++)
{
for(int j = i+1; j< colours.size(); j++)
{
if(colours.get(i).equals(colours.get(j))) // If duplicate found
{
colours.remove(j); // Removing duplicate
j--; // Moving one step back
}
}
}
}
}

Rubric-wise explanation


Point 1:

Look at line 26. We create the ...