How To Create ArrayList In Java

In earlier post Java arraylist examples have explain how to create arraylist java  , declaring arraylist in java and different methods of arraylist in java in brief. In this post we will discuss different way to create arraylist java  and arraylist add method. We have four different type constructor of arraylist in java. If you don’t know how to arraylist work internally so first read this arraylist java . We have three type constructor of arraylist as explain here .
1. ArrayList() : This Constructs create an empty list with an initial capacity of ten.
2. ArrayList(Collection<? extends E> c) :  This Constructs take list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
3. ArrayList(int initialCapacity) : This Constructs an empty list with the specified initial capacity.
Now we will create arraylist using these constructor.let’s see this by code.
import java.util.ArrayList;

public class ArraylistCreate {
	public static void main(String[] args) {
		
		/*
		 * Constructs an empty list with an initial capacity of ten.
		 */
		ArrayList<String> arr = new ArrayList<String>();
		// add element in arraylist
		arr.add("c");
		arr.add("php");
		arr.add("html");
		arr.add("java");
		// display arraylist
		System.out.println("arrayList is = " + arr);
		
		/*
		 * Constructs a list containing the elements of the 
		 * specified collection, in the order they are
		 *  returned by the collection's iterator.
		 */
		ArrayList<String> brr = new ArrayList<>(arr);
        //display arraylist
		System.out.println("arraylist is ="+ brr);
		
		/*
		 * Constructs an empty list with the specified
		 *  initial capacity.
		 */
		ArrayList<String> crr = new ArrayList<>(5);
		crr.add("php");
		crr.add("java");
               //display list 
               System.out.println("arraylist is ="+ crr);
		
	}
}
Output :
arrayList is = [c, php, html, java]
arraylist is =[c, php, html, java]
arraylist is =[php, java]

Leave a Reply

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

35 − 33 =