Java – ArrayList Example

ArrayList class is in java.util package of java. ArrayList is dynamic array which can grow automatically according to the required need. ArrayList does not require any fix dimension like String array and int array. ArrayList contains many useful methods. To add element in ArrayList, we can use add() method of ArrayList class. To add elements at fix position, we have to use add(index, object) method.

To get value from ArrayList, ArrayList provides get() method and ArrayList size() method. Size() method returns total number of elements in ArrayList.

Example of ArrayList in java

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        ArrayList<String> arlist=new ArrayList<String>();

        //<E> it is return type of ArrayList

        arlist.add("First Element"); // adding element in ArrayList
        arlist.add("Second Element");
        arlist.add("Third Element");
        arlist.add("forth Element");
        arlist.add("fifth Element");

        // add element with index for fix order  

        arlist.add(2, "Fixed Order of Element");

        // arlist.size() inform number of elements in ArrayList
        System.out.println("ArrayList Size :"+arlist.size());

        // get elements of ArrayList 
        for(int i=0;i<arlist.size();i++)
        {
            System.out.println("ArrayList Element "+i+" :"+arlist.get(i));
        }
    }
}

output

ArrayList Size :6
ArrayList Element 0 :First Element
ArrayList Element 1 :Second Element
ArrayList Element 2 :Fixed Order of Element
ArrayList Element 3 :Third Element
ArrayList Element 4 :forth Element
ArrayList Element 5 :fifth Element

Tags:

Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post