The grouping of objects in a single unit is called a collection. For example Array, Lists, Hashsets, etc. Data can be added from a specified collection in the current collection by using the addAll() method in Java. This method falls under the header file, java.util.*. The addAll() method returns a true value if the adding of the collection is successful after calling the method else it returns a false value.
We can use the addAll() method in two ways namely:
- The static method
- The instance method
Let there be 2 lists.
The static method Declaration
The instance method Declaration
Let the index where List2 needs to be inserted in List1 is 1.
The addAll() method always throws the following exceptions:
- NullPointerException: This exception is thrown if the specified or the current collection has null values.
- IllegalArgumentException: If the arguments of the specified collection have values that prevent them from being added to the current collection, this exception is thrown.
Input: boolean b = List1.addAll(large,extra-large) If the appending is successfull Output: true If the appending is unsuccessfull Output: false
Input: Collections.addAll(List1,List2) Output: List1 = [small,medium,large,extra-large]
- Initializing the two collections.
- Using the addAll() method to append the lists.
- Checking the boolean value of the method call.
- Printing the collections’ final values.
Below is the implementation of the above approach:
Initial collection value of list: [1, 2, 3] Initial collection value of list2: [4, 5, 6] Boolean Result: true Final collection value of list: [1, 2, 4, 5, 6, 3] Final collection value of list2: [4, 5, 6, 9, 8, 7, 6]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.