RemoveAll inside for is not removing elements. When I checked with where I get all the elements. This is weird,I thought foreach is immutable so I went with for and length of list.... anyone?
Loading
RemoveAll inside for is not removing elements. When I checked with where I get all the elements. This is weird,I thought foreach is immutable so I went with for and length of list.... anyone?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rajanikant HawaldarPosted Jun 14, 2021, 5:03 PM
Mallesh MalluPosted Jun 15, 2021, 7:09 AM
@Raj OK, @sachin I am looping list using for loop and inside loop I am trying to remove items using loop index with same list
Sachin SinghPosted Jun 14, 2021, 2:15 PM
Mallesh MalluPosted Jun 14, 2021, 1:59 PM
Rajanikant HawaldarPosted Jun 10, 2021, 11:23 AM
Pranam BhatPosted Jun 9, 2021, 5:30 AM
It basically removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists).
Also, it might be your objects are not equal! just their number field.
Override the equals method of your contacts class und use it to compare them.
ArrayList#removeAll(Collection) uses List#remove(Object) which uses equals.
Scenario:
How are 2 members determined to be equal? I'm guessing if they have the same ID, you deem them equal, however java wants them to be the exact same reference in memory which may not be the case. To correct for this you can override the equals function to have it return if the ids are equal:
public class Member {
//..
@Override
public boolean equals(Object anObject) {
if (!(anObject instanceof Member)) {
return false;
}
Member otherMember = (Member)anObject;
return otherMember.getUserUID().equals(getUserUID());
}
}
Also when you override .equals it is recommended to also override hashCode so that the objects also work correctly in hashing functions like Set or Map.