I have some problem with my Java code. I'm supposed to use loops and not any other method.
Say that my ArrayLis
t contains of
[Dog Cat Dog Dog Cat Dog Horse]
My goal is also to remove the copies of Dog and Cat so my final results equals
[Dog Cat Horse]
public void removeDouble(){
int counter = 0;
for (int i = 0 ; i < animals.size(); i++) {
for (int j = 1+i; j < animals.size() ; j++)
//don't start on the same word or you'll eliminate it.
if ( animals.get(j).equals( animals.get(i) ) ) {
animals.remove(animals.get(j));
counter++;
}
}
}
It feels like the "logic" is correct but my code does not work very well. Can somebody help me a little?
You can do like this.
In Java 8 we can use Stream API to remove duplicates, Like below snippet.
Working Example.
With Java 8 stream you can do as follows:
It would be simpler to start from the end of the list and decrement the counter. After removing the double at i, we can break without checking the whole string, because further doubles will be detected when i reaches j.
Moving backwards avoids the problem as you move forward the indexes have changed because you removed earlier elements (and you failed to adjust the index to take that into account).
Another problem with your logic you were using remove(object) rather than remove(index), which causes the first matching object to be removed. However, based on expected output, you want to preserve the order of the first matching objects. So instead you should have removed the last matching object, via index.
If you want to move forward rather than backwards, but you don't wish to make adjustments to the index after a removal, it is possible to make use of iterator's remove method:
Unfortunately the outer loop here cannot use an iterator because that would result in a ConcurrentModificationException.
Finally, you could also use a subList to solve it with a single explicit loop:
Your current code -
A simple way to do this is
Or using -
Thanks for all the answers. I still have a few problems, this is what i have came up with:
So now I'm starting the inner loop from the end of the ArrayList. Priority right now is only the get the loop working and then add remove etc.
Cheers!