Adding Array to Collections addAll()

Adding Array to Collections addAll()

Generally, in realtime, the names of the share holders etc, the programmer stores in the form an array. This array can be converted into a data structure with addAll() method of Collections class. addAll() method can also be used with a single element also.

Following is the method signature

  • static boolean addAll(Collection col1, Object obj1): Here, obj1 can be a single element or an array. Adds obj1 to the Collection col1.
Example on Adding Array to Collections addAll()

Adding Array to Collections addAll()
Output screenshot on Adding Array to Collections addAll()

Integer num[] = { new Integer(30), new Integer(40), new Integer(50) };

An array, num[], is created with three Integer objects of values 30, 40 and 50.

ArrayList firstList = new ArrayList();
firstList.add(10);

An ArrayList object firstList is created and added an element 10 as usual.

Collections.addAll(firstList, 20);
Collections.addAll(firstList, num);

With addAll() method a single element 20 and the array num are added. Now the firstList contains 10, 20 and the array elements 30, 40 and 50. Observe the output screenshot.

Similar operations are done with ArrayList with string array.

Leave a Reply

Your email address will not be published. Required fields are marked *