1

I'm trying to add all the elements of an ArrayList into another ArrayList,

I've tried using

if (!listTwo.isEmpty()){
    finalList.addAll(listTwo);
    }

finalList.addAll(listTwo);

However, this keeps sending me an NullPointerException error. Both are ArryList, and listTwo does have elements inside of it.

Any idea why it's sending this exception? Thanks a lot

4
  • 4
    Show us the exception. And perhaps finalList is null ? Commented Apr 16, 2014 at 23:04
  • have you initialized both your lists? Commented Apr 16, 2014 at 23:04
  • 1
    Check if finalList and listTwo are not nulls. They could be empty but not null. Commented Apr 16, 2014 at 23:05
  • If they are empty then you will not get a NPE. Commented Apr 16, 2014 at 23:23

1 Answer 1

5
finalList.addAll(listTwo);

Will add the elements from listTwo into finalList.

If you are getting a NullPointerException it is because one of your lists is null. Note that isEmpty() will throw a NullPointerException if the list is null, so that probably won't help you.

To check if the lists are null, do listTwo == null and/or finalList == null.

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

1 Comment

Thanks! I was initizalizing both of my ArrayList with null

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.