Example of ArrayList in Java
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());
Collections.sort(ArrayList object)
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); } } }
0 B A B C