ArrayList with Examples

ArrayList is a resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing theList interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
The sizeisEmptygetsetiterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedListimplementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:
   List list = Collections.synchronizedList(new ArrayList(...));

ArrayList Example :

1) Creating an ArrayList
You can use ArrayList in Java with or without Generics both are permitted by generics version is recommended because of enhanced type-safety.
In this example we will create an ArrayList of String in Java. This Java ArrayList will only allow String and will throw compilation error if we try to any other object than String.

ArrayList stringList = new ArrayList();

2) Putting an Item into ArrayList
Second line will result in compilation error because this Java ArrayList will only allow String elements.
stringList.add(new Integer(2)); //compilation error

3) Checking size of ArrayList
Size of an ArrayList in Java is total number of elements currently stored in ArrayList.
int size = stringList.size();

4) Checking Index of an Item in Java Arraylist
You can use indexOf() method of ArrayList in Java to find out index of a particular object.
int index = stringList.indexOf("Item");

5) Retrieving Item from arrayList in a loop
Many a times we need to traverse on Java ArrayList and perform some operations on each retrieved item. Here are two ways of doing it without using Iterator.
We will see use of Iterator in next section.

for (int i = 0; i
   String item = stringList.get(i);

From Java 5 onwards you can use foreach loop as well
for(String item: stringList){
System.out.println("retreived element: " + item);

6) Checking ArrayList for an Item
Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains () method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element.

7) Checking if ArrayList is Empty
We can use isEmpty() method of Java ArrayList to check whether ArrayList is empty. isEmpty() method returns true if this ArrayList contains no elements.

boolean result = stringList.isEmpty();

8) Removing an Item from ArrayList
There are two ways to remove any elements from ArrayList in Java. You can either remove an element based on its index or by providing object itself.
Remove remove (int index) and remove (Object o) method is used to remove any element from ArrayList in Java. Since ArrayList allows duplicate its worth noting that remove (Object o) removes the first occurrence of the specified element from this list, if it is present. In below code first call will remove first element from ArrayList while second call will remove first occurrence of item from ArrayList in Java.


9) Copying data from one ArrayList to another ArrayList in Java
Many a times you need to create a copy of ArrayList for this purpose you can use addAll(Collection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java. Below code will add all elements of stringList to newly created copyOfStringList.

ArrayList copyOfStringList = new ArrayList();

10) Replacing an element at a particular index
You can use set (int index, E element) method of java ArrayList to replace any element from a particular index. Below code will replace first element of stringList from "Item" to "Item2".


11) Clearing all data from ArrayList
ArrayList in Java provides clear () method which removes all of the elements from this list. Below code will remote all elements from our stringList and make the list empty. You can reuse Java ArrayListafter clearing it.


12) Converting from ArrayList to Array in Java
Java ArrayList provides you facility to get the array back from your ArrayList. You can use toArray(T[] a) method returns an array containing all of the elements in this list in proper sequence (from first to last element). "a" is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

String[] itemArray = new String[stringList.size()];
String[] returnedArray = stringList.toArray(itemArray);

13) Creating Synchronized ArrayList
Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use Collections utility class for this purpose as shown below.

List list = Collections.synchronizedList(new ArrayList(...));

14) Creating ArrayList from Array in Java
ArrayList in Java is amazing you can create even an ArrayList full of your element from an already existing array. You need to use Arrays.asList(T... a)  method for this purpose which returns a fixed-size list backed by the specified array.

ArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three");

15) Traversing in ArrayList in Java
You can use either Iterator or ListIterator for traversing on Java ArrayList. ListIterator will allow you to traverse in both directions while both Iterator and ListIterator will allow you to remove elements from ArrayList in Java while traversing.

Iterator itr = stringList.iterator();

ListIterator listItr = stringList.listIterator();

16) Sorting elements of ArrayList in Java
You can use Collections.sort(List list) method to sort a Java ArrayList in natural order defined by Comparable interface and can use Collections.sort(List list, Comparator c) method to sort your Java ArrayList based upon provided Comparator.

Some Important Points :
1) ArrayList is not a synchronized collection hence it is not suitable to be used between multiple threads concurrently. If you want to use ArrayList then you need to either use new CopyonWriteArrayList or use Collections.synchronizedList() to create a synchronized List.
2) CopyonWriteArrayList is recommended for concurrent multi-threading environment as it is optimized for multiple concurrent read and creates copy for write operation.
3) When ArrayList gets full it creates another array and uses System.arrayCopy() to copy all elements from one array to another array.
4) Iterator and ListIterator of java ArrayList are fail-fast it means if Arraylist is structurally modified at any time after the Iterator is created, in any way except through the iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, that's why it’s called fail-fast.
5) ConcurrentModificationException is not guaranteed and it only thrown at best effort.
6) If you are creating Synchronized List it’s recommended to create while creating instance of underlying ArrayList to prevent accidental unsynchronized access to the list.
7) An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation due to incremental filling of ArrayList.
8) The size, isEmpty, get, set, Iterator, and ListIterator operations run in constant time because ArrayList is based on Array but adding or removing an element is costly as compared to LinkedList.
9) ArrayList class is enhanced in Java5 to support Generics which added extra type-safety on ArrayList. It’s recommended to use generics version of ArrayList to ensure that your ArrayList contains only specified type of element and avoid any ClassCastException.
10) Since ArrayList implements List interface it maintains insertion order of element and allow duplicates.
11)If we set Arraylist reference null in Java all the elements inside Arraylist becomes eligible to garbage collection in java , provided there are no more reference exists for those objects.

Hope this Java ArrayList tutorial will be helpful for beginners in Java.

import java.util.*;

public class ArrayListDemo{
  public static void main(String[] args) {
  ArrayList<Object> arl=new ArrayList<Object>();
  Integer i1=new Integer(10);
  Integer i2=new Integer(20);
  Integer i3=new Integer(30);
  Integer i4=new Integer(40);
  String s1="tapan";
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  Integer i5=new Integer(50);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  Object a=arl.clone();
  System.out.println("The clone is: " + a);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email