I have the following code in java,
import java.util.ArrayList;
import java.util.Objects;
public class Cars {
private static ArrayList<String> replaceDuplicates(ArrayList<String> aList) {
for (int i = 0; i < aList.size(); i++) {
for (int j = i + 1; j < aList.size(); j++) {
if (Objects.equals(aList.get(i), aList.get(j))) {
aList.remove(i);
aList.add(i, "");
aList.remove(j);
aList.add(j, "");
}
}
}
return aList;
}
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<>();
cars.add("Ford");
cars.add("Ford");
cars.add("Hyundai");
cars.add("Toyota");
cars.add("Toyota");
cars.add("Toyota");
cars.add("Ford");
cars.add("Honda");
cars.add("GMC");
System.out.println(cars);
cars = replaceDuplicates(cars);
System.out.println(cars);
}
}
The output of this code is - [, , Hyundai, , , Toyota, Ford, Honda, GMC]
I want to replace the name of cars that appear more than once in the array list with a " ". For some reason, in my code if a car's name has appeared thrice in the array list, then the third occurrence isn't getting replaced by " ".
My desired output should be like this - [, , Hyundai, , , , , Honda, GMC]
What am I doing wrong here?
Thank you in advance!
[, , Hyundai, , , , , Honda, GMC], but not sure from your description.