java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to use ArrayList class?

In this example we'll learn how to use the java.util.ArrayList class. An ArrayList is part of the Java Collection Framework. By using this class we can create a dynamic size array of data.

package com.javacoderanch.example.util;

import java.util.ArrayList;
import java.util.List;
 
public class ArrayListExample
{
    public static void main(String[] args)
    {
        List list = new ArrayList();
 
        // adding items into array list
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
 
        // remove the third item from array list
        list.remove(2);
 
        // iterate array list item and print it
        for (int i = 0; i < list.size(); i++)
        {
            String item = (String) list.get(i);
            System.out.println("Item = " + item);
        }
 
        Object[] array = list.toArray();
    }
}

In the code above you have seen the demonstration on how to create an instance of ArrayList, adds some items, remove item and iterates through the entire ArrayList items.

When creating a class instance it is a good practice to use the interface as the type of variable instead of the concrete type directly. This can make you easily change your application if you don't want to use ArrayList anymore.