-1

I know this question has been asked many times before. But in my problem there are two arraylist of same object type. Let us say arraylist A contains 5 elements and arraylist B contains 2 elements.

Arraylist A elements = obj1,obj2,obj3,obj4,obj5

Arraylist B elements = obj1,obj2

What I want is I want to remove all the elements of Arraylist A that exist in arraylist B i.e obj1,obj2. Then the final Arraylist A should look like:

Arraylist A = obj3,obj4,obj5

The code I implemented:

for (int i=0;i<arraylistB.size();i++){
    if(arraylistA.contains(arraylistB.get(i))){
        arraylistA.remove(arraylistB.get(i));
        arraylistB.remove(i);
   }
}

But this code deleted nothing from Arraylist A, I don't know what I'm doing wrong. Please help me!

6
  • did you try removeAll ? Commented Mar 30, 2018 at 16:07
  • Yes, no success Commented Mar 30, 2018 at 16:09
  • 1
    What is the type of the elements? Is it a custom type? If so, did you override equals() and hashCode()? Commented Mar 30, 2018 at 16:09
  • 1
    Not easily as I’m using my phone. Someone will find a link for a duplicate in a few minutes. Commented Mar 30, 2018 at 16:11
  • 3
    Possible duplicate of ArrayList removeAll() not removing objects Commented Mar 30, 2018 at 16:16

2 Answers 2

3

You will need to override the equals() and hashcode() of class of Object1, Object2 etc which should be instances of the same class.

Then you can do a removeAll().

Sign up to request clarification or add additional context in comments.

Comments

1

Guessing the elements in arraylistA and arraylistB are not the same, meaning not reference to the same address, so this check is not correct

if(arraylistA.contains(arraylistB.get(i)))

Should check by e.g. id of the element instead.

3 Comments

Both arraylist have same object type
No, it does not
meaning that obj1 in arraylistA and obj1 in arraylistB are different. You can see it by checking both objects addresses via debugging.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.