Java beginner, so please bear with possibly silly questions.
I have a list of Strings which contains multiple duplicates and I want to detect and remove these duplicates. I know there's an easy way to do this with HashSet, and I've actually got it to work like that. But originally I was trying to do it in another way, also quite simple, in which there's something wrong and I don't understand what it is.
Given an array of strings with one duplicate, say {"A", "B", "C", "A"}, I can detect and replace the duplicate ("A" here). But if I have an array of strings with multiple duplicates, say {"A", "B", "C", "A", "E", "A"}, something goes wrong in the loop inside my method "replaceDuplicate()".
I need help to understand where the problem is in the following code:
public class TryTask_B2_Vector {
public static void main(String[] args) {
// Create array of strings for all the 'Gars':
String[] garList = new String[] {"A", "B", "C", "A", "E", "A"};
// Display the original "ArrayList" of 'Gars':
System.out.println("Original list of Gars: " + garList);
System.out.println();
bruteForce(garList);
System.out.println(bruteForce(garList));
System.out.println();
replaceDuplicate(garList);
System.out.println();
bruteForce(garList);
System.out.println(bruteForce(garList));
System.out.println();
System.out.println("New list of Gars: " + garList);
}
public static boolean bruteForce(String[] input){
for(int i=0; i < input.length; i++){
for(int j=0; j < input.length; j++){
if(input[i].equals(input[j]) && i != j){
return true;
}
}
}
return false;
}
public static String[] replaceDuplicate(String[] input){
for(int i=0; i < input.length; i++){
for(int j=0; j < input.length; j++){
if(input[i].equals(input[j]) && i != j){
input[j] = input[j].replace(input[j], "null");
System.out.println(input[j]);
}
}
}
return input;
}
}