What is ArrayList in java and how to create and all predefined methods and different ways to print ArrayList element?

Bharat KumarBharat Kumar
9 min read

In Java, ArrayList is a resizable-array implementation of the List interface. It's part of the java.util package. Unlike arrays, ArrayList can dynamically grow and shrink in size as elements are added or removed.

Here are some key characteristics of ArrayList:

  1. Dynamic Sizing: ArrayList can dynamically increase or decrease its size as elements are added or removed. You don't need to specify the size of the ArrayList initially.

  2. Indexed Access: Elements in an ArrayList can be accessed using an index, similar to arrays. The index starts from 0 for the first element and goes up to size-1 for the last element.

  3. Ordered Collection: ArrayList maintains the order of elements in which they are inserted.

  4. Allows Duplicates: ArrayList can contain duplicate elements.

  5. Not Synchronized: Unlike Vector, ArrayList is not synchronized. If multiple threads access an ArrayList concurrently and at least one of the threads modifies the list structurally, it must be synchronized externally.

  6. Null Elements: ArrayList allows storing null elements.

Different ways to create ArrayList:

In Java, you create an ArrayList using the ArrayList class provided in the java.util package.

Here are some ways to create an ArrayList:

  1. Default Constructor:
ArrayList<String> list1 = new ArrayList<>();
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

        ArrayList<String> arrayList = new ArrayList<>();
        System.out.println(arrayList); // Output: []
    }
}

2. With Initial Capacity:

ArrayList<String> list2 = new ArrayList<>(10); // Initial capacity of 10
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        int initialCapacity = 10;

        ArrayList<String> arrayList = new ArrayList<>(initialCapacity);
        System.out.println(arrayList); // Output: []
    }
}

3. From Existing Collection:

ArrayList<String> list3 = new ArrayList<>(Arrays.asList("item1", "item2", "item3"));
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> existingList = Arrays.asList("item1", "item2", "item3");

        ArrayList<String> arrayList = new ArrayList<>(existingList);
        System.out.println(arrayList); // Output: [item1, item2, item3]
    }
}

Commonly used methods of ArrayList:

Here are some of the most commonly used methods of ArrayList:

  1. add(E element): Adds the specified element to the end of the list.
import java.util.ArrayList;

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

        list.add("Apple");
        list.add("Banana");
        System.out.println(list); // Output: [Apple, Banana]
    }
}

2. add(int index, E element): Inserts the specified element at the specified position in the list.

import java.util.ArrayList;

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

        list.add("Apple");
        list.add(1, "Banana");
        System.out.println(list); // Output: [Apple, Banana]
    }
}

3. addAll(Collection<? extends E> c): Appends all elements of the specified collection to the end of the list.

import java.util.ArrayList;
import java.util.Arrays;

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

        list.add("Apple");
        list.addAll(Arrays.asList("Banana", "Orange"));
        System.out.println(list); // Output: [Apple, Banana, Orange]
    }
}

4. addAll(int index, Collection<? extends E> c): Inserts all elements of the specified collection into the list at the specified position.

import java.util.ArrayList;
import java.util.Arrays;

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

        list.add("Apple");
        list.addAll(1, Arrays.asList("Banana", "Orange"));
        System.out.println(list); // Output: [Apple, Banana, Orange]
    }
}

5. set(int index, E element) : It is used to replace the element at the specified position in the list with the specified element.

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        System.out.println("Before setting: " + list); // Output: [Apple, Banana, Orange]

        // Replace element at index 1 with "Grapes"
        String previousElement = list.set(1, "Grapes");

        System.out.println("Element replaced: " + previousElement); // Output: Banana
        System.out.println("After setting: " + list); // Output: [Apple, Grapes, Orange]
    }
}

6. get(int index): Returns the element at the specified index in the list.

import java.util.ArrayList;

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

        list.add("Apple");
        list.add("Banana");
        System.out.println(list.get(0)); // Output: Apple
    }
}

7. remove(int index): Removes the element at the specified index from the list.

import java.util.ArrayList;

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

        list.add("Apple");
        list.remove(0);
        System.out.println(list); // Output: []
    }
}

8. remove(Object o): Removes the first occurrence of the specified element from the list, if it is present.

import java.util.ArrayList;

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

        list.add("Apple");
        list.remove("Apple");
        System.out.println(list); // Output: []
    }
}

9. removeAll(Collection<?> c) : To remove all occurrences of elements from an ArrayList, you can use the removeAll(Collection<?> c) method. This method removes all elements from the list that are contained in the specified collection. It returns true if the list was modified as a result of this operation, otherwise false.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");
        list.add("Apple");
        list.add("Banana");

        System.out.println("Before removing: " + list); // Output: [Apple, Banana, Orange, Apple, Banana]

        ArrayList<String> elementsToRemove = new ArrayList<>();
        elementsToRemove.add("Apple");
        elementsToRemove.add("Banana");

        // Removing all occurrences of elementsToRemove from the list
        list.removeAll(elementsToRemove);

        System.out.println("After removing: " + list); // Output: [Orange]
    }
}
import java.util.ArrayList;
import java.util.Collections;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("A");
        list.add("D");
        list.add("A");

        System.out.println("Before removal: " + list); // Output: [A, B, C, A, D, A]

        list.removeAll(Collections.singleton("A"));

        System.out.println("After removal: " + list); // Output: [B, C, D]
    }
}

10. size(): Returns the number of elements in the list.

import java.util.ArrayList;

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

        list.add("Apple");
        System.out.println(list.size()); // Output: 1
    }
}

11. isEmpty(): Returns true if the list contains no elements.

import java.util.ArrayList;

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

        System.out.println(list.isEmpty()); // Output: true
    }
}

12. contains(Object o): Returns true if the list contains the specified element.

import java.util.ArrayList;

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

        list.add("Apple");
        System.out.println(list.contains("Apple")); // Output: true
    }
}

13. containsAll(Collection<?> c) : It is used to check if the list contains all of the elements of the specified collection. It returns true if the list contains all of the elements of the specified collection, otherwise, it returns false.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        ArrayList<String> checkList = new ArrayList<>();
        checkList.add("Apple");
        checkList.add("Banana");

        // Checking if list contains all elements of checkList
        boolean containsAll = list.containsAll(checkList);
        System.out.println("Contains all elements: " + containsAll); // Output: true

        checkList.add("Grapes");

        // Checking again if list contains all elements of modified checkList
        containsAll = list.containsAll(checkList);
        System.out.println("Contains all elements: " + containsAll); // Output: false
    }
}

14. clear(): Removes all elements from the list.

import java.util.ArrayList;

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

        list.add("Apple");
        list.clear();
        System.out.println(list); // Output: []
    }
}

15. clone(): Returns a shallow copy of the list.

import java.util.ArrayList;

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

        list.add("Apple");
        ArrayList<String> copy = (ArrayList<String>) list.clone();
        System.out.println(copy); // Output: [Apple]
    }
}

16. indexOf(Object o): Returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.

import java.util.ArrayList;

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

        list.add("Apple");
        list.add("Banana");
        list.add("Apple");
        System.out.println(list.indexOf("Apple")); // Output: 0
    }
}

17. lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in the list, or -1 if the list does not contain the element.

import java.util.ArrayList;

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

        list.add("Apple");
        list.add("Banana");
        list.add("Apple");
        System.out.println(list.lastIndexOf("Apple")); // Output: 2
    }
}

18. toArray(): Returns an array containing all of the elements in the list in proper sequence.

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");

        Object[] array = list.toArray();
        for (Object obj : array) {
            System.out.println(obj); // Output: Apple
        }
    }
}

19. toArray(T[] a): Returns an array containing all of the elements in the list in the correct order.

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");

        String[] array = list.toArray(new String[0]);
        for (String str : array) {
            System.out.println(str); // Output: Apple
        }
    }
}

20. subList(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        List<String> subList = list.subList(1, 3);
        System.out.println(subList); // Output: [Banana, Orange]
    }
}

Different ways to print ArrayList elements:

Printing an ArrayList in Java can be done in several ways, depending on your requirements and preferences. Here are some common methods along with examples and syntax:

  1. Using traditional for loop:
import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Using traditional for loop to print the ArrayList
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
}
/*Output:
Apple
Banana
Orange
*/

2. Using Enhanced for loop / for-each loop:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Using enhanced for loop to print the ArrayList
        for (String item : list) {
            System.out.println(item);
        }
    }
}
/*Output:
Apple
Banana
Orange
*/

3. Using forEach() method with lambda expression (Java 8 and later):

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Using forEach() method with lambda expression to print the ArrayList
        list.forEach(item -> System.out.println(item));
    }
}
/*Output:
Apple
Banana
Orange
*/

4. Using forEach() method with method reference (Java 8 and later):

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Using forEach() method with method reference to print the ArrayList
        list.forEach(System.out::println);
    }
}
/*Output:
Apple
Banana
Orange
*/

5. Using forEachRemaining() method:

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Obtain an iterator for the ArrayList
        Iterator<String> iterator = list.iterator();

        // Iterate over the remaining elements using forEachRemaining() method
        iterator.forEachRemaining(item -> System.out.println(item));
    }
}
/*Output:
Apple
Banana
Orange
*/

6. Using Iterator:

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Obtain an iterator for the ArrayList
        Iterator<String> iterator = list.iterator();

        // Iterate over the elements using the iterator
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
/*Output:
Apple
Banana
Orange
*/

7. Using toString() method:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Using toString() method to print the ArrayList
        System.out.println(list.toString());  // Output: [Apple, Banana, Orange]
    }
}

8. Using ListIterator:

import java.util.ArrayList;
import java.util.ListIterator;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        ListIterator<String> iterator = list.listIterator();

        // Forward iteration
        System.out.println("Forward iteration:");
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Backward iteration
        System.out.println("Backward iteration:");
        while (iterator.hasPrevious()) {
            System.out.println(iterator.previous());
        }
    }
}
/* Output:
Forward iteration:
Apple
Banana
Orange
Backward iteration:
Orange
Banana
Apple
*/
1
Subscribe to my newsletter

Read articles from Bharat Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bharat Kumar
Bharat Kumar

I am a frontend developer.