Problems to delete repeated numbers in an Arraylist<String>

Asked

Viewed 212 times

3

I’m having trouble getting repeated numbers out of a ArrayList, here is the code snippet:

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 some more, I really wanted to know what’s wrong with this code, because I can’t figure out.

  • 2

    Delete more or less? I can’t imagine why you would be deleting more, could you give an example of where it happens?

  • 1

    Numbers stored as string?

  • and if you use a set?

  • 3

    You are removing elements during iteration. This gives problem because it messes up the contents.

  • What is the type of the list? You can put more parts of the code?

  • 1

    Did any of the answers solve the problem? Do you think you can accept one of them? See [tour] how to do this. You’d be helping the community by identifying the best solution. You can only accept one of them, but you can vote for anything on the entire site.

Show 1 more comment

2 answers

6

You cannot remove items from the object being iterated, because it happens to have another structure during the initiated iteration. You have to create an auxiliary structure. If you want to do it yourself and not use a HashSet:

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

4


The data structure you are using is not ideal for what you want to do. I don’t know why you are using Arraylist, but if you need the structure not to accept repeated values the ideal is to use Set so you don’t have to do additional treatments and make the code cleaner.

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

    public void add (String house){
        // nunca aceitará valor repetido
        houses.add(house);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.