Java ArrayList(Storing elements to ArrayList)

 Java ArrayList


To create a ArrayList use: ArrayList<datatype> a=new ArrayList<datatype>();


Example 1: This code will show you How to create a ArrayList


% ====================== YOUR CODE HERE ====================== import java.util.*; public class ArrayListEg{ public static void main(String args[]){ ArrayList<String> c1=new ArrayList<String>(); c1.add("element 1"); c1.add("element 2"); c1.add("element 3"); System.out.println(c1); } }

Output:

[element 1, element 2, element 3]


example 2:This code will show you how to iterate through the ArrayList using two methods.

method 1: for loop

method 2: Enhanced for loop

import java.util.*;
public class ArrayListEg{
    public static void main(String args[]){
        ArrayList<String> c1=new ArrayList<String>();
        
        c1.add("I");
        c1.add("AM");
        c1.add("BATMAN");
        
        //using for loop
        for(int i=0;i<c1.size();i++){
             System.out.print(c1.get(i)+" ");
        }
        
        //using enhanced for loop
        for(String e:c1){
            System.out.print(e+" ");
        }
    }
 }

Output:

I AM BATMAN
I AM BATMAN


Thank you.

Comments