CodesJava

Easy learning with example program codes

how to add all elements of a list to arraylist in java?


ArrayList:

ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing elements. It maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.

Note: ArrayList provides the facility of random access because of it is index based.

The addAll() method is used to add all elements of a list to arraylist in java.

Example:

package com.codesjava;
 
import java.util.ArrayList;
import java.util.List;
 
public class Test {
  public static void main(String args[]){
	ArrayList<String> arrayList = new ArrayList<String>();
	arrayList.add("Jai");
	arrayList.add("Mahesh");
	arrayList.add("Vivek");
	arrayList.add("Naren");
	arrayList.add("Hemant");
	arrayList.add("Vishal");
	System.out.println("Actual ArrayList:"+arrayList);
	List<String> list = new ArrayList<String>();
        list.add("Vikas");
        list.add("Lalit");
        arrayList.addAll(list);
        System.out.println("After adding list elements: "+arrayList);
  }
}

Output

Actual ArrayList:[Jai, Mahesh, Vivek, Naren, Hemant, Vishal]
After adding list elements: [Jai, Mahesh, Vivek, Naren, Hemant, Vishal, Vikas, Lalit]


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap