addAll() method

addAll() method: This java addall list method employs to add all elements of a collection to another collection.

 boolean addAll(Collection<? extends E> c);

Where, c is the collection which you want to add in this collection.
return type:  Its return type is boolean. It can return either true or false.

How addAll() method can work: We have different types of collections like ArrayList, hashset etc. Each collection has some set of rules. Some collection doesn’t allow duplicate elements, but some are allowing. So, the addAll() method can behave differently and it works according to the class in which it is implemented.

For example: The Java addAll list method is implemented in Hashset class is not able to add any duplicate collection in another collection. Because Hashset deosn’t supports the duplicate elements.But the addAll() method behaves different for the ArrayList class because it is also implemented in ArrayList class and ArrayList can add the duplicate elements. So, you can add duplicate collections.

This method can throw different types of exceptions:

UnsupportedOperationException, If the add all operation is not allowed in this collection.
ClassCastException, If the class of the specified element prevents it from being added to this collection.
NullPointerException, If the specified collection is null or it contains null elements and the collection does not allow null elements.
IllegalArgumentException, if some property of the element of collection prevents it from being added to another collection.
IllegalStateException, If all the element can’t be added at this time due to insertion restrictions.

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.