Problems deleting repeated numbers in an ArrayListString

3

I'm having trouble extracting repeated numbers from a ArrayList , here's the snippet of code:

for( int i = 0 ; i < houses.size(); i++ ) {   
   for( int j = 1; j < houses.size(); j++ ) {
        if(houses.get(i).equals(houses.get(j)) && i!=j){
            houses.remove(j);
        }
    }
 }

It correctly deletes most of the repeated elements, but in some cases deletes a few more, I really wanted to know what's wrong with this code, as I can not figure it out.

    
asked by anonymous 29.01.2016 / 19:51

2 answers

3

The data structure you are using is not ideal for what you want to do. I do not know the reason for using ArrayList, but if you need the structure does not accept repeated values it is best to use the Set so that you do not have to do additional treatments and leave the code cleaner.

    Set<String> houses = new HashSet<>();

    public void add (String house){
        // nunca aceitará valor repetido
        houses.add(house);
    }
    
30.01.2016 / 19:34
5

You can not remove items from the object being iterated because it passes through another structure during the iteration started. You have to create an auxiliary structure. If you want to do it on the same hand and do not use a HashSet :

ArrayList<String> aux = new ArrayList<String>();
for (String item : houses) {
    if (!aux.contains(item)) {
        aux.add(item);
    }
}
houses = aux;

See working on ideone .

    
29.01.2016 / 20:42