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.
Delete more or less? I can’t imagine why you would be deleting more, could you give an example of where it happens?
– Math
Numbers stored as string?
– user28595
and if you use a set?
– Pilati
You are removing elements during iteration. This gives problem because it messes up the contents.
– Pablo Almeida
What is the type of the list? You can put more parts of the code?
– Maniero
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.
– Maniero