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()
import java.util.*;
public class CollectionsAddAll
{
  public static void main(String args[])
  {
    Integer num[] = { new Integer(30), new Integer(40), new Integer(50)  };
    ArrayList firstList = new ArrayList();
    firstList.add(10);
    
    Collections.addAll(firstList, 20);       // adding one element
    Collections.addAll(firstList, num);      // adding an array
    System.out.println("firstList elements: " + firstList);

    String numbers[] = { "three", "four", "five" };
    ArrayList secondList = new ArrayList();
    secondList.add("one");
    
    Collections.addAll(secondList, "two");    // adding one element
    Collections.addAll(secondList, numbers);  // adding an array
    System.out.println("\nsecondList elements: " + secondList);
  }
}

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 Comment

Your email address will not be published.