简体   繁体   中英

How to add all elements of an ArrayList into another ArrayList in java

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM