Just a disclaimer: I repeated my java mod for the second time so my questions may tend to be a bit simple and hopefully I don't sound too stupid.
Write a method removeDuplicates that takes as a parameter a sorted ArrayList of Strings and that eliminates any duplicates from the list. For example, suppose that a variable called list contains the following values:
{"be", "be", "is", "not", "or", "question", "that", "the", "to", "to"}
After calling removeDuplicates(list); the list should store the following values:{"be", "is", "not", "or", "question", "that", "the", "to"}
Because the values will be sorted, all of the duplicates will be grouped together.
My attempt at this:
public static void removeDuplicates(ArrayList <String>a){
for(int i=0;i<a.size();i++){
String word=a.get(i);
String word2=a.get(i+1);
if(word.equals(word2)){
a.remove(word);
}
else{
System.out.print(word);
}
}
}
The issue is that when I call it with:
["duplicate", "duplicate", "duplicate", "duplicate", "duplicate"]
it returns indexoutofbound
. I understand it has something to do with i=i-1
with reference to the remove
method. Tried inserting it here and there but it doesn't work. But I am very puzzled as this works with my code. When I call it with:
["be", "be", "is", "not", "or", "question", "that", "the", "to", "to"]
it works.