Java ArrayList

In Java ArrayList is a class which is available in java.util package. ArrayList uses a dynamic array for storing the elements. ArrayList work as an array, but there is no size limit. ArrayList is more flexible than traditional array.

There are some key points to remember about ArrayList:

  1. ArrayList inherits AbstractList class and implements the List interface.
  2. Initially ArrayList will be created with some specific size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection.
  3. We can store duplicate elements in ArrayList.
  4. ArrayList will maintains the insertion order.
  5. ArrayList is non synchronized.
  6. ArrayList works on index basis, so we can access the elements randomly.
  7. In case of manipulation ArrayList is slower than LinkedList because lot of shifting needs to occur if any element is removed from the array list.
  8. While creating an ArrayList using generic type it will not support the primitive type such as byte, short, int, long, float, double, char, boolean. Instead we need to use the wrapper classes.

Creating an ArrayList

    List list = new ArrayList();
            (or)
    ArrayList arrayList = new ArrayList();

In above we have created an ArrayList. Inside this ArrayList object we can store multiple types of elements.

Creating an ArrayList of a specific type

    // create Integer type arraylist
    ArrayList<Integer> arrayList = new ArrayList<Integer>();

    // create String type arraylist
    ArrayList<String> arrayList = new ArrayList<String>();

In above we have created an ArrayList of two different types integer and string.

  1. If we create an ArrayList using Integer type then we can store only Integer type of element.
  2. If we create an ArrayList using String type then we can store only String type of element.

ArrayList constructos
Constructor Description Example
ArrayList() This constructor is used to build an empty array list. ArrayList arr = new ArrayList();
ArrayList(Collection c) This constructor is used to build an array list initialized with the elements from the collection c ArrayList arr = new ArrayList(c);
ArrayList(int capacity) This constructor is used to build an array list with initial capacity being specified ArrayList arr = new ArrayList(20);
Methods of ArrayList class

There are some basic commonly used methods are:

Method Name Description
add() This method is use to add the elements to the ArrayList.
get() This method is use to fetch the elements from the ArrayList.
set() This method is use to update the elements in an ArrayList.
remove() This method is use to remove an elements from the ArrayList.
size() Returns the length of the arraylist.
sort() Sort the arraylist elements.
clone() Creates a new arraylist with the same element, size, and capacity.
contains() Searches the arraylist for the specified element and returns a boolean result.
ensureCapacity() Specifies the total element the arraylist can contain.
idEmpty() Checks if the arraylist is empty.
indexOf() Searches a specified element in an arraylist and returns the index of the element.
Basic Operations on ArrayList

The ArrayList class provides various methods to perform different operations on arraylists. We will look at some commonly used arraylist operations.

  1. ▪ Add elements
  2. ▪ Access elements
  3. ▪ Change elements
  4. ▪ Remove elements

Add elements:

To add a single element to the arraylist, we use the add() method of the ArrayList class. For example,


  import java.util.ArrayList;

  public class ArrayListAddExample {
      public static void main(String[] args){
          // create ArrayList
          ArrayList<String> languages = new ArrayList<String>();

          // add() method without the index parameter
          languages.add("Java");
          languages.add("C");
          languages.add("Python");
          System.out.println("ArrayList: " + languages);
      }
  }
Access elements:

To access an element from the arraylist, we use the get() method of the ArrayList class. For example,


    import java.util.ArrayList;

    public class ArrayListAccessExample {
        public static void main(String[] args){
            // create ArrayList
            ArrayList<String> animals = new ArrayList<String>();

            // add() method without the index parameter
            animals.add("Cat");
            animals.add("Dog");
            animals.add("Cow");
            System.out.println("ArrayList: " + animals);

            // get the element from the arraylist
            String str = animals.get(1);
            System.out.print("Element at index 1: " + str);
        }
    }
Change elements:

To change elements of the arraylist, we use the set() method of the ArrayList class. For example,


    import java.util.ArrayList;

    public class ArrayListChangeExample {
      public static void main(String[] args) {
        ArrayList<String> languages = new ArrayList<>();
    
        // add elements in the array list
        languages.add("Java");
        languages.add("Kotlin");
        languages.add("C++");
        System.out.println("ArrayList: " + languages);
    
        // change the element of the array list
        languages.set(2, "JavaScript");
        System.out.println("Modified ArrayList: " + languages);
      }
    }
Remove elements:

To remove an element from the arraylist, we can use the remove() method of the ArrayList class. For example,


    import java.util.ArrayList;

    public class ArrayListRemoveExample {
    public static void main(String[] args) {
        ArrayList<String> languages = new ArrayList<>();

        // add elements in the array list
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayList: " + animals);

        // remove element from index 2
        String str = animals.remove(2);
        System.out.println("Updated ArrayList: " + animals);
        System.out.println("Removed Element: " + str);
    }
    }
Differences between array and ArrayList:
Array ArrayList
Array is collection of simillar data type elements. ArrayList is a collection of object where we can store multiple types or same types of objects.
Array is static in size. ArrayList is dynamic in size.
Array is a fixed length of data structure. ArrayList is a variable length data structure. It can be resize itself when needed.
It is mandatory to provide the size of an array while initializing it directly or indirectly. We can create an instance of ArrayList without specifying its size. Java creates ArrayList of default size.
It performs fast in comparison to ArrayList because of fixed size. ArrayList is internally backed by the array in Java. The resize operation in ArrayList slows down the performance.
An array can store both objects and primitives type. We cannot store primitive type in ArrayList. It automatically converts primitive type to object.
We cannot use generics along with array because it is not a convertible type of array. ArrayList allows us to store only generic/ type, that's why it is type-safe.
Array provides a length variable which denotes the length of an array. ArrayList provides the size() method to determine the size of ArrayList.
We can add elements in an array by using the assignment operator. Java provides the add() method to add elements in the ArrayList.
Array can be multi-dimensional. ArrayList is always single-dimensional.