ArrayList in Java

ArrayList is most widely used collections API for storing the list of objects. This class is equivalent to Vector, except that it is unsynchronized. Look at the below important points about the class ArrayList.

  • It allows null values
  • It stores the duplicate elements
  • The size of the list is grows dynamically when more elements are added.
  • It has capacity, which tells the list about how many empty elements has to be created while initializing the object. Note that, ArrayList internally uses array to store the values.
  • An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation.
  • Array list is not synchronized, which is the only distinguishing factor from Vector.
  • The retrieval is random access since it is working on arrays.
  • ArrayList maintains the insertion order of the elements.

ArrayList Example

package javabeat.net.core;

import java.util.ArrayList;

public class ArrayListExample {
	public static void main(String args[]){
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("Element 1");
		arrayList.add("Element 2");
		arrayList.add("Element 3");

		//Index based retrival
		System.out.println("Get Element at 0 index : "+arrayList.get(0));

		//Iteration
		for (String str : arrayList){
			System.out.println(str);
		}

		//Remove a element using index
		arrayList.remove(1);
		System.out.println("Removed element at index 1");

		ArrayList<String> arrayList2 = new ArrayList<String>();
		arrayList2.add("Test Element 1");

		//Add another collection
		arrayList.addAll(arrayList2);
		System.out.println("Added Collections");
		//Iteration
		for (String str : arrayList){
			System.out.println(str);
		}

	}
}

Output of the above example will be:

Get Element at 0 index : Element 1
Element 1
Element 2
Element 3
Removed element at index 1
Added Collections
Element 1
Element 3
Test Element 1

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*