Remove duplicates in ArrayList - Java

2020-05-06 10:53发布

I have some problem with my Java code. I'm supposed to use loops and not any other method. Say that my ArrayList 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?

8条回答
等我变得足够好
2楼-- · 2020-05-06 11:46

The logic for the inner loop is incorrect.

You will skip items every time you have the same item appear consecutively in the list.

Say you had "dog", "dog", "dog", "cat". When you remove the "dog" at index 1, the list now becomes "dog", "dog", "cat".

The problem is that your "j" index is now incremented to 2 so the next test will access the "cat" item, not the "dog" item. So every time you remove an item you are skipping the next item in the list which is why you get inconsistent results.

The solution is to either:

  1. decrement the j variable every time you remove an item
  2. start the inner loop from the end of the list and count down backwards toward 0.
查看更多
We Are One
3楼-- · 2020-05-06 11:46

Your removing the items as you are iterating over them, have an array that holds indexes, and when you find a double, add the index to the indexes array. Iterate over the indexes array and delete from the animals arraylist.

查看更多
登录 后发表回答