ArrayList in java

Let’s learn arraylist in java.

ArrayList in java

  • java ArrayList allows duplicate elements.
  • Java ArrayList preserves insertion order.
  • java ArrayList is widely used because of its functionality and flexibility. It is designed to hold heterogeneous collections of objects.
  • Java ArrayList can have any number of null values.
  • Java ArrayList is part of collection framework.
  • Java Arraylist implements list interface.
  • ArrayList is a re-sizable array that grows dynamically when elements are added and decreased when elements are deleted.
  • For frequent retrieving operation java ArrayList is the best. Because ArrayList elements are stored in consecutive memory locations.
  • ArrayList cannot hold primitive data types such as int, double, char, and long.
  • ArrayList can hold String and wrapper class objects (Double, Integer).
  • ArrayList is index based; we can randomly access elements using index positions.
  • Java ArrayList class implements RandomAccess interface.

Here’s an example on java arraylist.

import java.util.ArrayList;
public class ArrayListExample
{
   public static void main(String[] args)
   {
      int num = 14;
      // declaring ArrayList with initial size num
      ArrayList<Integer> al = new ArrayList<Integer>(num);
      // append new element at the end of list
      for(int a = 1; a <= num; a++)
      {
         al.add(a);
      }
      System.out.println(al);
      // remove element at index 7
      al.remove(7);
      // print ArrayList after deletion
      System.out.println(al);
      // print elements one by one
      for(int a = 0; a < al.size(); a++)
      {
         System.out.print(al.get(a) + " ");
      }
   }
}


Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14]
1 2 3 4 5 6 7 9 10 11 12 13 14


Arraylist methods

MethodsDescription
boolean addAll(Collection <? extends E> c)appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
void add(int index, E element)inserts the specified element at the specified position in this list.
boolean addAll( int index, Collection <? extends E> c)inserts all of the elements in the specified collection into this list at the specified position.
void trimToSize()trim the capacity of the instance of the ArrayList to the list’s current size.
boolean remove(Object o)removes the first occurrence of the specified element from this list, if it is present.
boolean removeAll(Collection<?> c)removes from this list all of its elements that are contained in the specified collection.
boolean retainAll(Collection<?> c)retains only the elements in this list that are contained the specified collection.
Object clone()returns a shallow copy of this ArrayList instance.
boolean contains(Object o)returns true if this list contains the specified element.
boolean containsAll(Collection c)returns true if this list contains all of the elements of the specified collection.
E get(int index)returns the element at the specified position in this list.
int indexOf(Object o)returns the index of the first occurrence of the specified element in this list, or – 1 if this list does not contain the element.
int lastIndexOf(Object o)returns the index of the last occurrence of the specified element in this list, or – 1 if this list does not contain the element.
void clear()removes all of the elements from this list.
boolean isEmpty()returns true if this list contains no elements.
int size()returns the number of elements in this list.
List<E> subList(int fromIndex, int toIndex)returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Iterator<E> iterator()returns an iterator over the elements in this list in proper sequence.
ListIterator<E> listIterator()returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E> listIterator(int index)returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
Object[] toArray()returns an array containing all of the elements in this list in proper sequence (from first to last element).
void ensureCapacity(int minCapacity)Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
void forEach(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
protected void removeRange(int fromIndex, int toIndex)Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
E set(int index, E element)Replaces the element at the specified position in this list with the specified element.
Spliterator<E> spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this list.

Arraylist constructors

  • ArrayList a = new ArrayList() – creates empty ArrayList object with default initial capacity 10.
  • ArrayList a = new ArrayList(Collection c) – this one is parameterized constructor which accepts collection. It will create the arraylist from any collection object.
  • ArrayList a = new ArrayList(int initialCapacity) – this accepts “int” value. it creates empty lists with the specified initial capacity.

Hierarchy of java arraylist

arraylist in java

Java Iterate ArrayList or loop through ArrayList

Let’s see how to iterate or loop through ArrayList using for-each loop and for loop.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListIterateDemo 
{
   public static void main(String[] args) 
   {
      ArrayList<String> birds = new ArrayList<String>();
      birds.add("Sparrow");
      birds.add("Pigeon");
      birds.add("Peacock");
      birds.add("Eagle");
      System.out.println("Using for-each loop: ");
      for(String s: birds) 
      {
         System.out.println(s);
      }
      System.out.println("Using for loop: ");
      for(int a = 0; a < birds.size(); a++) 
      {
         System.out.println(birds.get(a));
      }
   }
}


Output:

Using for-each loop:
Sparrow
Pigeon
Peacock
Eagle

Using for loop:
Sparrow
Pigeon
Peacock
Eagle


Sorting an ArrayList of strings

To sort an java arraylist there is sort() method of Collections class of java.util package which sorts alphabets and numerals.

Let’s see an example to sort an ArrayList of strings.

import java.util.ArrayList;
import java.util.Collections;
public class ArrayListStrings
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Banana");
      al.add("Pineapple");
      al.add("Jackfruit");
      al.add("Apple");
      Collections.sort(al);
      for(String str : al)
      {
         System.out.println(str);
      }
   }
}


Output:

Apple
Banana
Jackfruit
Pineapple


Let’s see an example to sort an ArrayList of Integers.

import java.util.ArrayList;
import java.util.Collections;
public class ArrayListIntegers
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(86);
      al.add(22);
      al.add(61);
      al.add(83);
      al.add(59);
      al.add(39);
      Collections.sort(al);
      for(int num : al)
      {
         System.out.println(num);
      }
   }
}


Output:

22
39
59
61
83
86

Reference – Oracle docs