0

I have two ArrayLists

ArrayList<Integer> values = new ArrayList<Integer>();
values.add(9);

That's one, here's the other:

ArrayList<Integer> values2 = new ArrayList<Integer>();
for(int j = 1; j < 10; j++){
        values2.add(j);
    }

How can I compare the two and remove 9 from the second ArrayList? I tried using a foreach statement but I kept getting

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 9, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)

This had been a head-peck for some hours now and I appreciate any help you can offer

1 Answer 1

8

You use

values2.removeAll(values);

From the Javadoc for the Collection interface (http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html) -

boolean removeAll(Collection c)

Removes all of this collection's elements that are also contained in the specified collection (optional operation). After this call returns, this collection will contain no elements in common with the specified collection.

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

2 Comments

Gonna slam my head against a brick wall now, thanks bro. My profile picture is so relevant right now.
@MattKnowles Happens to the best of us. As long as the docs are your first source, you'll be fine in the long run.

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.