Home  >  Core Java

Example of ArrayList in Java

By Arvind Rai, May 18, 2013
ArrayList is a collection to store object which is not thread safe. ArrayList can be set with a minimum size and when needed more, size will be increased automatically. ArrayList behaves as an array with variable size. ArrayList is an ordered collection. ArrayList maintains the order in which object has been added. If we wish to synchronize ArrayList we can do as below.
List list = Collections.synchronizedList(new ArrayList());
 
ArrayList does not maintain uniqueness. As ArrayList is an ordered collection but we can do sorting by
Collections.sort(ArrayList object)
 
ArrayListDemo.java
package com.util;
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo {
    public static void main(String[] args) {
        int minCapacity=10;
        List<String> arrList = new ArrayList<String>(minCapacity);
        arrList.add("A");
        arrList.add("B");
        //add value by index.
        arrList.add(2,"C");
        //get index of value
        System.out.println(arrList.indexOf("A"));
        //get value by index
        System.out.println(arrList.get(1));
        //iterate ArrayList
        for(String s:arrList){
            System.out.println(s);
        }
    }
}
Output
0
B
A
B
C 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us