Java ArrayList Tutorial

by Dimitris Tasios
137 views

In this article, we will learn about what a Java ArrayList is and how to use its methods through examples. Here, we will cover more practical matters. On the contrary, if you would like to read about lists in Java, in theory, you might want to refer to our Java List article instead.

1. What is an ArrayList

An ArrayList is a list of items with an index, which can be used to access it within the collection, just like in simple arrays. The main difference with arrays, though, is that an ArrayList has a dynamic size. This means that the size of an ArrayList can be increased or decreased based on our needs. On the other hand, arrays, whose size must be declared at initialization and cannot be changed afterward.

ArrayList inherits from AbstractList class and implements the List interface. It can be found in the java.util package.

1.1 A Visualization of ArrayList in Java

You can think of an ArrayList as a collection of sequential items that have a position (or index), as shown below:

Figure 1. An ArrayList with names

In the figure above you could easily retrieve the second name or, in reverse, you could find out in which position “Lucy” is located within the list.

1.2 Overview of Java ArrayList

In brief, ArrayList in Java has the following characteristics:

  • Its size can change according to our operations on it; it can get larger, smaller and even empty.
  • It can accept null values and duplicate values.
  • When iterating through the collection, we can be sure that the items will be accessed at the same order each time.
  • Accessing operations are O(1) while modifying operations are O(n), with n being the number of elements of the ArrayList.

2. Initializing an ArrayList in Java

We can initialize an ArrayList in 3 ways.

  1. As an empty ArrayList, by using the ArrayList() constructor.
  2. From another Collection, with the ArrayList(Collection c) constructor. The order of items depends on the way the Collection‘s iterator accessed the elements.
  3. With an inital capacity, with the help of the ArrayList(int initialCapacity) constructor. If the initial capacity is used, then the ArrayList will increase its size. By having an inital capacity, we can save some CPU cycles, leading to a better optimization of operations.

2.1 ArrayList()

This is the simplest way to initialize an ArrayList. Its initial capacity is 10. We will cover the “add” method later.

    private static void constructSimpleArrayList() {
        /* Initialize a simple ArrayList of colors (String).*/
        ArrayList<String> colors = new ArrayList<>();
        colors.add("red");
        colors.add("green");
        colors.add("blue");

        System.out.println("Printing for \"constructSimpleArrayList\" method");
        colors.stream().forEach(System.out::println);
        System.out.println();
    }

Output

red
green
blue

2.2 ArrayList(Collection c)

By using this constructor, we can create an ArrayList by using another Collection (not necessarily from another ArrayList). Here we convert the values of a HashMap into an ArrayList.

    private static void constructArrayListFromAnotherCollection() {
        /* Initialize a simple HashMap of with key of type String and value of type String.*/

        HashMap<String, String> continentsAndCountries = new HashMap<>();
        continentsAndCountries.put("Europe", "Greece");
        continentsAndCountries.put("North America", "USA");
        continentsAndCountries.put("Asia", "Japan");

        /* Create an ArrayList from the HashMap's values*/
        ArrayList countries = new ArrayList(continentsAndCountries.values());
        System.out.println("Printing for \"constructArrayListFromAnotherCollection\" method");
        countries.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Japan
Greece
USA

2.3 ArrayList(int initialCapacity)

Lastly, with this constructor, we can create an ArrayList with an initial capacity. Normally, the size of an ArrayList shouldn’t be an issue, but we have the ability to make a few optimizations by providing an expected size for the ArrayList. By doing that, we could avoid allocating more space to our ArrayList than required.

private static void constructArrayListWithInitialCapacity() {
        /* Initialize an ArrayList with an inital capacity*/

        ArrayList<Integer> evenNumbers = new ArrayList(3);
        evenNumbers.add(0);
        evenNumbers.add(2);
        evenNumbers.add(4);

        System.out.println("Printing for \"constructArrayListWithInitialCapacity\" method, at capacity 3.");
        evenNumbers.stream().forEach(System.out::println);
        System.out.println();

        /* We can add more numbers without any problems. The ArrayList's size will simply increase.*/
        evenNumbers.add(200);
        evenNumbers.add(404);

        System.out.println("Printing for \"constructArrayListWithInitialCapacity\" method, with increased capacity.");
        evenNumbers.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "constructArrayListWithInitialCapacity" method, at capacity 3.
0
2
4

Printing for "constructArrayListWithInitialCapacity" method, with increased capacity.
0
2
4
200
404

3. Methods of Java ArrayList

In this section, we will go through all methods provided by the ArrayList class with examples.

3.1 Adding Items to ArrayList in Java

Firstly, let’s see the methods that add or insert elements into an ArrayList. Any method that uses an index as a parameter, will throw an IndexOutOfBoundsException if the index is less than zero or greater than or equal to the ArrayList‘s size.

3.1.1 boolean add(E e)

Adds an element at the end of the ArrayList.

  • Parameters: an item e of type E, which must be the same as the type of the ArrayList.
  • Returns true.
    private static void add() {
        ArrayList<String> names = new ArrayList<>();

        System.out.println("Printing for \"add\" method, empty ArrayList");
        names.stream().forEach(System.out::println);
        System.out.println();

        names.add("Dimitris");
        names.add("Akis");
        names.add("Ignis");

        System.out.println("Printing for \"add\" method, after adding elements");
        names.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "add" method, empty ArrayList

Printing for "add" method, after adding elements
Dimitris
Akis
Ignis

3.1.2 void add(int index, E element)

Adds an element at a specific index (position) of the ArrayList.

  • Parameters: the item of type E and the index of the ArrayList to add the item.
  • Returns: nothing.
private static void addAtIndex() {
        ArrayList<String> names = new ArrayList<>();

        names.add("Dimitris");
        names.add("Akis");
        names.add("Ignis");

        System.out.println("Printing for \"addAtIndex\" method, initially");
        names.stream().forEach(System.out::println);
        System.out.println();

        // inserting a new element in 2nd position
        names.add(1,"Katerina");

        System.out.println("Printing for \"addAtIndex\" method, after inserting an element at index = 1");
        names.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "addAtIndex" method, initially
Dimitris
Akis
Ignis

Printing for "addAtIndex" method, after inserting an element at index = 1
Dimitris
Katerina
Akis
Ignis

3.1.3 boolean addAll(Collection c)

Adds all elements of one Collection into the ArrayList, at the end of the latter. The order of the items in the ArrayList depends on the order that the Collection‘s iterator accessed the items.

  • Parameters: the Collection whose items will be added at the end of the ArrayList.
  • Returns: true, if the operation was successful. For ArrayList, it could only return false if the Collection is empty (no change happened).
    private static void addAllAtTheEnd() {
        // create an ArrayList of European countries
        ArrayList<String> europeanCountries = new ArrayList<>();

        europeanCountries.add("Greece");
        europeanCountries.add("Spain");
        europeanCountries.add("Italy");

        System.out.println("Printing for \"addAllAtTheEnd\" method, initially");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();

        // creating a new ArrayList of more European countries
        ArrayList<String> moreEuropeanCountries = new ArrayList<>();

        moreEuropeanCountries.add("Lithuania");
        moreEuropeanCountries.add("Austria");
        moreEuropeanCountries.add("Hungary");

        // add all new countries in our first ArrayList
        europeanCountries.addAll(moreEuropeanCountries);
        System.out.println("Printing for \"addAllAtTheEnd\" method, after inserting the new countries");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "addAllAtTheEnd" method, initially
Greece
Spain
Italy

Printing for "addAllAtTheEnd" method, after inserting the new countries
Greece
Spain
Italy
Lithuania
Austria
Hungary

3.1.4 boolean addAll(int index, Collection c)

Inserts all elements of one Collection into the ArrayList, at the specified position. The order of the items in the ArrayList depends on the order that the Collection‘s iterator accessed the items.

  • Parameters: the Collection whose items will be added at the specified index of the ArrayList.
  • Returns: true, if the operation was successful.
private static void addAllAtIndex() {
        // create an ArrayList of European countries
        ArrayList<String> europeanCountries = new ArrayList<>();

        europeanCountries.add("Greece");
        europeanCountries.add("Spain");
        europeanCountries.add("Italy");

        System.out.println("Printing for \"addAllAtIndex\" method, initially");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();

        // creating a new ArrayList of more European countries
        ArrayList<String> moreEuropeanCountries = new ArrayList<>();

        moreEuropeanCountries.add("Lithuania");
        moreEuropeanCountries.add("Austria");
        moreEuropeanCountries.add("Hungary");

        // add all new countries in our first ArrayList, at the specified position
        europeanCountries.addAll(1, moreEuropeanCountries);

        System.out.println("Printing for \"addAllAtIndex\" method, after inserting the new countries");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "addAllAtIndex" method, initially
Greece
Spain
Italy

Printing for "addAllAtIndex" method, after inserting the new countries, at index = 1
Greece
Lithuania
Austria
Hungary
Spain
Italy

3.2 Removing Items from Java ArrayList

Here, we will examine the methods that remove elements from an ArrayList.

3.2.1 E remove(int index)

Removes the element from the specified position. All subsequent elements are shifted one place, so as to fill the empty spot.

  • Parameters: the position of the element that will be removed.
  • Returns: the element that was removed from the ArrayList.
    private static void removeAtIndex() {
        // create an ArrayList of European countries
        ArrayList<String> europeanCountries = new ArrayList<>();

        europeanCountries.add("Greece");
        europeanCountries.add("Lithuania");
        europeanCountries.add("Spain");
        europeanCountries.add("Italy");

        System.out.println("Printing for \"removeAtIndex\" method, initially");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();

        /* removing the second element. Notice that the ArrayList will have a smaller size by one element.
           Also, the "Spain" became the 2nd element and "Italy" the third (shifted by one place to cover the empty spot) */
        europeanCountries.remove(1);

        System.out.println("Printing for \"removeAtIndex\" method, after removing the country at index = 1");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "removeAtIndex" method, initially
Greece
Lithuania
Spain
Italy

Printing for "removeAtIndex" method, after removing the country at index = 1
Greece
Spain
Italy

3.2.2 boolean remove(Object o)

Removes the first element that is the same as the Object, in other words, the first occurrence of Object o. If the Object does not exist, then the ArrayList remains unchanged.

  • Parameters: the Object to be removed.
  • Returns: true, if the ArrayList contained the Object.
private static void removeElementIfExists() {
        // create an ArrayList of European countries
        ArrayList<String> europeanCountries = new ArrayList<>();

        europeanCountries.add("Greece");
        europeanCountries.add("Lithuania");
        europeanCountries.add("Spain");
        europeanCountries.add("Italy");

        System.out.println("Printing for \"removeElementIfExists\" method, initially");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();

        /* removing "Italy" and then "Germany". "Italy" was removed because it existed in the ArrayList, but "Germany"
        wasn't because it didn't exist in the first place. */
        europeanCountries.remove("Italy");
        europeanCountries.remove("Germany");

        System.out.println("Printing for \"removeElementIfExists\" method, after trying to remove \"Italy\" and \"Germany\"");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "removeElementIfExists" method, initially
Greece
Lithuania
Spain
Italy

Printing for "removeElementIfExists" method, after trying to remove "Italy" and "Germany"
Greece
Lithuania
Spain

3.2.3 boolean removeAll(Collection c)

Removes all elements in the ArrayList that are also contained in the Collection c.

  • Parameters: the Collection used to remove elements from ArrayList.
  • Returns: true, if the ArrayList was modified due to this operation.
    private static void removeAllElementsFromCollection() {
        // create an ArrayList of European countries
        ArrayList<String> europeanCountries = new ArrayList<>();

        europeanCountries.add("Greece");
        europeanCountries.add("Lithuania");
        europeanCountries.add("Spain");
        europeanCountries.add("Italy");

        System.out.println("Printing for \"removeAllElementsFromCollection\" method, initially");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();

        /* create an ArrayList that contains the Baltic countries. */
        ArrayList<String> balticCountries = new ArrayList<>();

        balticCountries.add("Estonia");
        balticCountries.add("Lithuania");
        balticCountries.add("Latvia");

        /* remove all european countries that are also baltic*/
        europeanCountries.removeAll(balticCountries);

        System.out.println("Printing for \"removeAllElementsFromCollection\" method, after all baltic countries were removed");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "removeAllElementsFromCollection" method, initially
Greece
Lithuania
Spain
Italy

Printing for "removeAllElementsFromCollection" method, after all baltic countries were removed
Greece
Spain
Italy

3.2.4 boolean retainAll(Collection c)

Removes all elements in the ArrayList that are not contained in Collection c. It’s the opposite operation of removeAll(Collection c).

  • Parameters: the Collection used to retain elements in the ArrayList.
  • Returns: true, if the ArrayList was modified due to this operation.
    private static void retainAllElementsFromCollection() {
        // create an ArrayList of European countries
        ArrayList<String> europeanCountries = new ArrayList<>();

        europeanCountries.add("Greece");
        europeanCountries.add("Lithuania");
        europeanCountries.add("Spain");
        europeanCountries.add("Italy");

        System.out.println("Printing for \"retainAllElementsFromCollection\" method, initially");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();

        /* create an ArrayList that contains the Baltic countries. */
        ArrayList<String> balticCountries = new ArrayList<>();

        balticCountries.add("Estonia");
        balticCountries.add("Lithuania");
        balticCountries.add("Latvia");

        /* remove all european countries that are not baltic*/
        europeanCountries.retainAll(balticCountries);

        System.out.println("Printing for \"retainAllElementsFromCollection\" method, after all non baltic countries were removed");
        europeanCountries.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "retainAllElementsFromCollection" method, initially
Greece
Lithuania
Spain
Italy

Printing for "retainAllElementsFromCollection" method, after all non baltic countries were removed
Lithuania

3.2.5 boolean removeIf(Predicate filter)

Removes all elements in the ArrayList that satisfy the Predicate filter.

  • Parameters: a filter that returns true if the elements satisfy it.
  • Returns: true, if any element is removed from the ArrayList.
    private static void removeAllElementsThatSatisfyFilter() {
        // create an ArrayList of numbers
        ArrayList<Integer> numbers = new ArrayList<>();

        numbers.add(15);
        numbers.add(20);
        numbers.add(1);
        numbers.add(30);

        System.out.println("Printing for \"removeAllElementsThatSatisfyFilter\" method, initially");
        numbers.stream().forEach(System.out::println);
        System.out.println();

        /* remove all numbers that are greater than 15. */
        numbers.removeIf(n -> n > 15);

        System.out.println("Printing for \"removeAllElementsThatSatisfyFilter\" method, after removing all numbers greater than 15");
        numbers.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "removeAllElementsThatSatisfyFilter" method, initially
15
20
1
30

Printing for "removeAllElementsThatSatisfyFilter" method, after removing all numbers greater than 15
15
1

3.2.6 protected void removeRange(int fromIndex, int toIndex)

Removes all elements from the position fromIndex inclusive up to toIndex exclusive. If both indices are the same, then this method has no effect. Note that this method must be used by a class that extends ArrayList because this method is protected.

  • Parameters: an index indicating the beginning and another index indicating one position after the end of the desired range.
  • Returns: nothing.
    public static void removeAllInRange() {
        /* Because "removeRange" method is protected, any class using it must extend ArrayList.
        *  In our case, "ArrayListRemovingMethodsExampleClass" class is wrapper class for an ArrayList<String>
        *  In the examples above, we could replace all ArrayList<String> with the following statement. */

        // create an ArrayList of greek capital letters
        ArrayListRemovingMethodsExampleClass greekLetters = new ArrayListRemovingMethodsExampleClass();

        greekLetters.add("Δ"); // index = 0
        greekLetters.add("Σ"); // index = 1
        greekLetters.add("Ω"); // index = 2 <- this will be removed
        greekLetters.add("Ψ"); // index = 3 <- this will be removed
        greekLetters.add("Γ"); // index = 4 <- this will be removed
        greekLetters.add("Λ"); // index = 5 <- this will be removed
        greekLetters.add("Π"); // index = 6 <- this will NOT be removed
        greekLetters.add("Ξ"); // index = 7


        System.out.println("Printing for \"removeAllInRange\" method, initially");
        greekLetters.stream().forEach(System.out::println);
        System.out.println();

        /* remove all letters 4 letters, starting from index = 2. */
        greekLetters.removeRange(2,6);

        System.out.println("Printing for \"removeAllInRange\" method, after removing all letters between indices 2 and 6 (exclusive)");
        greekLetters.stream().forEach(System.out::println);
        System.out.println();

        /* example of same first and last index; no effect will happen */
        greekLetters.removeRange(1,1);

        System.out.println("Printing for \"removeAllInRange\" method, after trying to remove elements in a range with same first and last index");
        greekLetters.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "removeAllInRange" method, initially
Δ
Σ
Ω
Ψ
Γ
Λ
Π
Ξ

Printing for "removeAllInRange" method, after removing all letters between indices 2 and 6 (exclusive)
Δ
Σ
Π
Ξ

Printing for "removeAllInRange" method, after trying to remove elements in a range with same first and last index
Δ
Σ
Π
Ξ

3.2.7 void clear()

Removes all elements in the ArrayList. The ArrayList will be empty after this operation, as if it was just initialized.

  • Parameters: none.
  • Returns: nothing.
    private static void clearAll() {
        // create an ArrayList of colors
        ArrayList<String> colors = new ArrayList<>();

        colors.add("magenta");
        colors.add("cyan");
        colors.add("yellow");

        System.out.println("Printing for \"clearAll\" method, initially");
        colors.stream().forEach(System.out::println);
        System.out.println();

        /* remove all numbers that are greater than 15. */
        colors.clear();
        
        System.out.println("Printing for \"clearAll\" method, after all elements have been removed");
        colors.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "clearAll" method, initially
magenta
cyan
yellow

Printing for "clearAll" method, after all elements have been removed

3.3 Informative Methods About ArrayList in Java

In this section, we will take a look into various methods that provide some kind of information about the ArrayList.

3.3.1 boolean contains(Object o)

Checks whether the ArrayList contains the Object o.

  • Parameters: The Object to check whether it exists in the ArrayList.
  • Returns: true, if the Object exists in the ArrayList.
    private static void containsElement() {
        /* create an ArrayList of languages*/
        ArrayList<String> languages = new ArrayList<>();

        languages.add("English");
        languages.add("Italiano");
        languages.add("Español");
        languages.add("Deutsch");

        System.out.println("Printing for \"containsElement\" method, initially");
        languages.stream().forEach(System.out::println);
        System.out.println();

        /* check whether greek and spanish exist in the ArrayList*/
        boolean containsGreek = languages.contains("Ελληνικά");
        boolean containsSpanish = languages.contains("Español");

        /* print the result*/
        System.out.println("Printing for \"containsElement\" method, checking whether those two languages exist in the ArrayList");
        System.out.println("Greek in ArrayList: " + containsGreek);
        System.out.println("Spanish in ArrayList: " + containsSpanish);
        System.out.println();
    }

Output

Printing for "containsElement" method, initially
English
Italiano
Español
Deutsch

Printing for "containsElement" method, checking whether those two languages exist in the ArrayList
Greek in ArrayList: false
Spanish in ArrayList: true

3.3.2 E get(int index)

Returns the element at the specific index. The element is not removed from the ArrayList.

  • Parameters: the index of the item in the ArrayList that should be retrieved.
  • Returns: the element in the index‘s position.
    private static void getElement() {
        /* create an ArrayList of languages*/
        ArrayList<String> languages = new ArrayList<>();

        languages.add("English");
        languages.add("Italiano");
        languages.add("Español");
        languages.add("Deutsch");

        System.out.println("Printing for \"getElement\" method, initially");
        languages.stream().forEach(System.out::println);
        System.out.println();

        /* get the second language in the ArrayList. The element is not removed from the ArrayList, so it's size will be the same*/
        String secondLanguage = languages.get(1);

        /* print the result*/
        System.out.println("Printing for \"getElement\" method, after getting the second language");
        System.out.println("Second language: " + secondLanguage);
        System.out.println();

        /* The size of the ArrayList did not change; there are still four languages in it.*/
        System.out.println("Printing for \"getElement\" method, ArrayList is unchanged");
        languages.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "getElement" method, initially
English
Italiano
Español
Deutsch

Printing for "getElement" method, after getting the second language
Second language: Italiano

Printing for "getElement" method, ArrayList is unchanged
English
Italiano
Español
Deutsch

3.3.3 int indexOf(Object o)

Returns the index of the first occurrence of Object o. If the element doesn’t exist, -1 is returned instead.

  • Parameters: the Object to locate in the ArrayList.
  • Returns: the index of the Object in the ArrayList, or -1 if it doesn’t exist.
    private static void indexOfElement() {
        /* create an ArrayList of rooms in a house*/
        ArrayList<String> roomsInHouse = new ArrayList<>();

        roomsInHouse.add("living room");
        roomsInHouse.add("bedroom");
        roomsInHouse.add("bathroom");
        roomsInHouse.add("kitchen");
        roomsInHouse.add("bedroom");
        roomsInHouse.add("bedroom");

        System.out.println("Printing for \"indexOfElement\" method, initially");
        roomsInHouse.stream().forEach(System.out::println);
        System.out.println();

        /* get the index of bedroom. Notice that the first occurrence will be returned*/
        int firstBedroom = roomsInHouse.indexOf("bedroom");

        /* print the result*/
        System.out.println("Printing for \"indexOfElement\" method, the first index of bedroom");
        System.out.println("The first bedroom is located at index: " + firstBedroom);
        System.out.println();
    }

Output

Printing for "indexOfElement" method, initially
living room
bedroom
bathroom
kitchen
bedroom
bedroom

Printing for "indexOfElement" method, the first index of bedroom
The first bedroom is located at index: 1

3.3.4 int lastIndexOf(Object o)

Returns the index of the last occurrence of Object o. If the element doesn’t exist, -1 is returned instead.

  • Parameters: the Object to locate in the ArrayList.
  • Returns: the index of the Object in the ArrayList, or -1 if it doesn’t exist.
    private static void lastIndexOfElement() {
        /* create an ArrayList of rooms in a house*/
        ArrayList<String> roomsInHouse = new ArrayList<>();

        roomsInHouse.add("living room");
        roomsInHouse.add("bedroom");
        roomsInHouse.add("bathroom");
        roomsInHouse.add("kitchen");
        roomsInHouse.add("bedroom");
        roomsInHouse.add("bedroom");

        System.out.println("Printing for \"lastIndexOfElement\" method, initially");
        roomsInHouse.stream().forEach(System.out::println);
        System.out.println();

        /* get the index of bedroom. Notice that the last occurrence will be returned*/
        int lastBedroom = roomsInHouse.lastIndexOf("bedroom");

        /* print the result*/
        System.out.println("Printing for \"lastIndexOfElement\" method, the last index of bedroom");
        System.out.println("The last bedroom is located at index: " + lastBedroom);
        System.out.println();
    }

Output

Printing for "lastIndexOfElement" method, initially
living room
bedroom
bathroom
kitchen
bedroom
bedroom

Printing for "lastIndexOfElement" method, the last index of bedroom
The last bedroom is located at index: 5

3.3.5 boolean isEmpty()

Returns true if the ArrayList contains no elements.

  • Parameters: none.
  • Returns: true, if the ArrayList has no elements.
    private static void isEmpty() {
        /* create an ArrayList of the contents of a drawer*/
        ArrayList<String> upperDrawer = new ArrayList<>();

        upperDrawer.add("books");
        upperDrawer.add("pens");
        upperDrawer.add("notebooks");

        /* create an ArrayList of the contents of another drawer*/
        ArrayList<String> lowerDrawer = new ArrayList<>();

        System.out.println("Printing for \"isEmpty\" method, upper drawer's contents");
        upperDrawer.stream().forEach(System.out::println);
        System.out.println();

        System.out.println("Printing for \"isEmpty\" method, lower drawer's contents");
        lowerDrawer.stream().forEach(System.out::println);
        System.out.println();

        boolean isUpperDrawerEmpty = upperDrawer.isEmpty();
        boolean isLowerDrawerEmpty = lowerDrawer.isEmpty();

        /* print the result*/
        System.out.println("Printing for \"isEmpty\" method, whether the drawers are empty");
        System.out.println("Is the upper drawer empty -> " + isUpperDrawerEmpty);
        System.out.println("Is the lower drawer empty -> " + isLowerDrawerEmpty);
        System.out.println();
    }

Output

Printing for "isEmpty" method, upper drawer's contents
books
pens
notebooks

Printing for "isEmpty" method, lower drawer's contents

Printing for "isEmpty" method, whether the drawers are empty
Is the upper drawer empty -> false
Is the lower drawer empty -> true

3.3.6 int size()

Returns the number of elements in the ArrayList.

  • Parameters: none.
  • Returns: the numbers of items in the ArrayList.
    private static void size() {
        /* create an ArrayList of the contents of a bookcase*/
        ArrayList<String> bookcase = new ArrayList<>();

        bookcase.add("Geography book");
        bookcase.add("Math book");
        bookcase.add("English book");
        bookcase.add("Chemistry book");

        System.out.println("Printing for \"size\" method, bookcase's contents");
        bookcase.stream().forEach(System.out::println);
        System.out.println();

        int numberOfBooks = bookcase.size();

        /* print the result*/
        System.out.println("Printing for \"size\" method, the number of books in the bookcase");
        System.out.println("The bookcase has " + numberOfBooks + " books");
        System.out.println();
    }

Output

Printing for "size" method, bookcase's contents
Geography book
Math book
English book
Chemistry book

Printing for "size" method, the number of books in the bookcase
The bookcase has 4 books

3.4 Methods That Replace Elements in Arraylist

The methods included in this section are used to replace one or more elements in an ArrayList, without altering its size.

3.4.1 void replaceAll(UnaryOperator operator)

Replaces all elements in the ArrayList with elements determined by the UnaryOperator operator.

  • Parameters: the UnaryOperator to apply to each element in ArrayList.
  • Returns: nothing.
    public static void replaceAll() {
        /* create an ArrayList of numbers*/
        ArrayList<Integer> numbers = new ArrayList<>();

        numbers.add(3);
        numbers.add(12);
        numbers.add(0);
        numbers.add(-43);
        numbers.add(-9);

        System.out.println("Printing for \"replaceAll\" method, bookcase's contents");
        numbers.stream().forEach(System.out::println);
        System.out.println();

        /* replace all numbers with their triple value*/
        numbers.replaceAll(n -> n * 3);

        /* print the result*/
        System.out.println("Printing for \"replaceAll\" method, all values are replaced by their tripled values");
        numbers.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "replaceAll" method, bookcase's contents
3
12
0
-43
-9

Printing for "replaceAll" method, all values are replaced by their tripled values
9
36
0
-129
-27

3.4.2 E set(int index, E element)

Replaces the element of the ArrayList at the specified index, with a new element.

  • Parameters: the index of the element that will be replaced and the element to take its place.
  • Returns: the element that was replaced.
    public static void set() {
        /* create an ArrayList of planets*/
        ArrayList<String> planets = new ArrayList<>();

        planets.add("Earth");
        planets.add("Pluto");
        planets.add("Mercury");
        planets.add("Venus");


        System.out.println("Printing for \"set\" method, some planets of our Solar System");
        planets.stream().forEach(System.out::println);
        System.out.println();

        /* replace Pluto with Mars*/
        planets.set(1, "Mars");

        /* print the result*/
        System.out.println("Printing for \"set\" method, Mars replacing Pluto");
        planets.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "set" method, some planets of our Solar System
Earth
Pluto
Mercury
Venus

Printing for "set" method, Mars replacing Pluto
Earth
Mars
Mercury
Venus

3.5 Cloning Methods

This section includes methods that use an ArrayList in order to create another Collection.

3.5.1 List subList(int fromIndex, int toIndex)

By using a start and an end index of ArrayList, a new view is created with all elements between those two indices. Being a view means that any changes on the new List will be reflected on the initial ArrayList. So, additions, deletions, and replacements are all reflected back at the ArrayList.

  • Parameters: the starting index (inclusive) and the ending index (exclusive) of ArrayList which are used to create a new List.
  • Returns: the new List specified by the two indices.
    private static void subList() {
        /* create an ArrayList of car brands*/
        ArrayList<String> carBrands = new ArrayList<>();

        carBrands.add("Toyota");
        carBrands.add("Lamborghini");
        carBrands.add("Ferrari");
        carBrands.add("Fiat");

        System.out.println("Printing for \"subList\" method, all car brands");
        carBrands.stream().forEach(System.out::println);
        System.out.println();

        /* create a List of expensive car brands*/
        List<String> expensiveCarBrands = carBrands.subList(1,3);

        /* print the new List*/
        System.out.println("Printing for \"subList\" method, only expensive car brands");
        expensiveCarBrands.stream().forEach(System.out::println);
        System.out.println();

        /* Let's modify the new List, replace Lamborghini with Audi*/
        expensiveCarBrands.set(0, "Audi");

        /* Expensive car brands for reference*/
        System.out.println("---------------------------------------------------------------------------------------------------------");
        System.out.println("Printing for \"subList\" method, modification on expensive car brands List");
        expensiveCarBrands.stream().forEach(System.out::println);
        System.out.println();

        /* print the initial List.*/
        System.out.println("Printing for \"subList\" method, all car brands list has changed. Lamborghini has been replaced by Audi");
        carBrands.stream().forEach(System.out::println);
        System.out.println();

        /* Now let's add a new brand and print the initial ArrayList again*/
        expensiveCarBrands.add("Mercedes");

        /* Expensive car brands for reference*/
        System.out.println("---------------------------------------------------------------------------------------------------------");
        System.out.println("Printing for \"subList\" method, addition on expensive car brands List");
        expensiveCarBrands.stream().forEach(System.out::println);
        System.out.println();

        System.out.println("Printing for \"subList\" method, all car brands list has a new element, which is placed at the end of the newly created expensive car brands List");
        carBrands.stream().forEach(System.out::println);
        System.out.println();

        /* Finally, removing an expensive car brand will also remove it from the initial ArrayList*/
        expensiveCarBrands.remove(1);

        /* Expensive car brands for reference*/
        System.out.println("---------------------------------------------------------------------------------------------------------");
        System.out.println("Printing for \"subList\" method, deletion on expensive car brands List");
        expensiveCarBrands.stream().forEach(System.out::println);
        System.out.println();

        System.out.println("Printing for \"subList\" method, all car brands list has one less element; Ferrari has been removed");
        carBrands.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "subList" method, all car brands
Toyota
Lamborghini
Ferrari
Fiat

Printing for "subList" method, only expensive car brands
Lamborghini
Ferrari

---------------------------------------------------------------------------------------------------------
Printing for "subList" method, modification on expensive car brands List
Audi
Ferrari

Printing for "subList" method, all car brands list has changed. Lamborghini has been replaced by Audi
Toyota
Audi
Ferrari
Fiat

---------------------------------------------------------------------------------------------------------
Printing for "subList" method, addition on expensive car brands List
Audi
Ferrari
Mercedes

Printing for "subList" method, all car brands list has a new element, which is placed at the end of the newly created expensive car brands List
Toyota
Audi
Ferrari
Mercedes
Fiat

---------------------------------------------------------------------------------------------------------
Printing for "subList" method, deletion on expensive car brands List
Audi
Mercedes

Printing for "subList" method, all car brands list has one less element; Ferrari has been removed
Toyota
Audi
Mercedes
Fiat

3.5.2 Object[] toArray()

Returns an Array of type Object[], created using the ArrayList. The order of the elements in the Array is the same as in the ArrayList. Because of the Object[] type, in order to use it with any other class, we have to typecast it. Otherwise, we will get a compilation error.

If we wanted to use a String[] or an Integer[] Array directly, it would be better to use the T[] toArray(T[] a) method, described in the next subsection. Despite that, there is a workaround of creating an Array with the same length as the ArrayList‘s size and then populating it manually using a for loop.

  • Parameters: none.
  • Returns: an Object[] Array of the ArrayList.
    private static void toArrayNoArgument() {
        /* create an ArrayList of US states*/
        ArrayList<String> usStates = new ArrayList<>();

        usStates.add("New York");
        usStates.add("California");
        usStates.add("Texas");
        usStates.add("Nevada");

        System.out.println("Printing for \"toArrayNoArgument\" method, the initial ArrayList of US states");
        usStates.stream().forEach(System.out::println);
        System.out.println();

        /* create an Object[] Array containing the states*/
        Object[] usStatesArray = usStates.toArray();

        System.out.println("Printing for \"toArrayNoArgument\" method, the Object[] Array populated with toArray()");
        for(int i = 0; i < usStatesArray.length; i++) {
            System.out.println(usStatesArray[i]);
        }
        System.out.println();

        /* with the following we would get a compile time error. Uncomment to check it out*/
//        String[] usStatesArrayCompileTimeError = usStates.toArray();

        /* and with the following we would get a runtime exception, ClassCastException. Uncomment to check it out*/
//        String[] usStatesArrayRuntimeError = (String[]) usStates.toArray();

        /* so, in order to use a String[] Array directly, we would have to use the toArray(T[] a) method, not this one*/

        /* of course, it's possible to use a for loop to get an Array out of an ArrayList like so:*/

        /* firstly, create a String[] with the same size as the ArrayList*/
        String[] usStatesStringArray = new String[usStates.size()];

        /* and then use a for loop to populate the newly created String[] Array*/
        System.out.println("Printing for \"toArrayNoArgument\" method, the String[] Array, populated with a 'for' loop");
        for(int i = 0; i < usStatesStringArray.length; i++) {
            usStatesStringArray[i] = usStates.get(i);
            System.out.println(usStatesStringArray[i]);
        }
        System.out.println();
    }

Output

Printing for "toArrayNoArgument" method, the initial ArrayList of US states
New York
California
Texas
Nevada

Printing for "toArrayNoArgument" method, the Object[] Array populated with toArray()
New York
California
Texas
Nevada

Printing for "toArrayNoArgument" method, the String[] Array, populated with a 'for' loop
New York
California
Texas
Nevada


Process finished with exit code 0

3.5.3 T[] toArray(T[] a)

Returns an Array of type Object[], created using the ArrayList, in proper order. The difference here is that we have to pass the targeted array as an argument. This is done so that toArray() knows the type of the Array to return. In other words, unless we pass an Object[] Array as the parameter, this method will not get an Object[] array, but the specific type of Array we wanted, directly.

  • Parameters: the targeted array, used to determine the type of the array to return.
  • Returns: the targeted array, it’s the same Array as the one used as a parameter.
    private static void toArrayWithArgument() {
        /* create an ArrayList of US states*/
        ArrayList<String> usStates = new ArrayList<>();

        usStates.add("New York");
        usStates.add("California");
        usStates.add("Texas");
        usStates.add("Nevada");

        System.out.println("Printing for \"toArrayWithArgument\" method, the initial ArrayList of US states");
        usStates.stream().forEach(System.out::println);
        System.out.println();

        /* create a String[] with the same size as the ArrayList*/
        String[] usStatesStringArray = new String[usStates.size()];

        /* use the toArray method, passing our newly created, empty Array*/
        usStatesStringArray = usStates.toArray(usStatesStringArray);

        /* print the result*/
        System.out.println("Printing for \"toArrayWithArgument\" method, the String[] Array, populated with the toArray(String[]) method");
        for(int i = 0; i < usStatesStringArray.length; i++) {
            System.out.println(usStatesStringArray[i]);
        }
        System.out.println();
    }

Output

Printing for "toArrayWithArgument" method, the initial ArrayList of US states
New York
California
Texas
Nevada

Printing for "toArrayWithArgument" method, the String[] Array, populated with the toArray(String[]) method
New York
California
Texas
Nevada

3.5.4 Object clone()

Clones the ArrayList, using a shallow copy. This means that the list is copied, not also the elements. As a result, changing the elements of the cloned ArrayList should also change the ones in the initial ArrayList. This does not apply to immutable types, like Integer or String, since in their case, the two lists appear to be independent.

  • Parameters: none.
  • Returns: a shallow copy of ArrayList.
    private static void cloneArrayList() {
        /* create an ArrayList of US states*/
        ArrayList<String> usStates = new ArrayList<>();

        usStates.add("New York");
        usStates.add("California");
        usStates.add("Texas");
        usStates.add("Nevada");

        System.out.println("Printing for \"cloneArrayList\" method, the initial ArrayList of US states");
        usStates.stream().forEach(System.out::println);
        System.out.println();

        /* create a new generic ArrayList that is a copy of the initial ArrayList*/
        ArrayList copyOfUsStates = new ArrayList<>();

        /* we have to typecast it, because clone returns an Object*/
        copyOfUsStates = (ArrayList) usStates.clone();
        
        /* print the result*/
        System.out.println("Printing for \"cloneArrayList\" method, the clone of ArrayList of US states");
        copyOfUsStates.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "cloneArrayList" method, the initial ArrayList of US states
New York
California
Texas
Nevada

Printing for "cloneArrayList" method, the clone of ArrayList of US states
New York
California
Texas
Nevada


Process finished with exit code 0

3.6 Iterator Methods

3.6.1 Iterator iterator()

Returns an Iterator over the ArrayList. An Iterator is an interface that can run through collections and perform actions, such as accessing the elements or removing them. It begins traversing from the first element of the ArrayList. The traversal is one-way (from the first element to the last). So, it’s not possible to perform a traversal in the opposite direction. This interface is also part of the java.util package.

  • Parameters: none.
  • Returns: an Iterator over the ArrayList.
    private static void iterator() {
        /* create an ArrayList of Italian cities*/
        ArrayList<String> italianCities = new ArrayList<>();

        italianCities.add("Napoli");
        italianCities.add("Roma");
        italianCities.add("Firenze");
        italianCities.add("Mestre");

        System.out.println("Printing for \"iterator\" method, the initial ArrayList of Italian cities printed without iterator");
        italianCities.stream().forEach(System.out::println);
        System.out.println();

        /* create an Iterator over the ArrayList. It starts from index = 0*/
        Iterator italianCitiesIterator = italianCities.iterator();

        /* printing the elements again, this time using our iterator*/
        System.out.println("Printing for \"iterator\" method, the ArrayList of Italian cities printed with iterator");

        /* hasNext() is used to check whether the iterator has reached the end of the ArrayList*/
        while(italianCitiesIterator.hasNext()) {

            /* next() return the next element of the ArrayList*/
            System.out.println(italianCitiesIterator.next());
        }
        System.out.println();
    }

Output

Printing for "iterator" method, the initial ArrayList of Italian cities printed without iterator
Napoli
Roma
Firenze
Mestre

Printing for "iterator" method, the ArrayList of Italian cities printed with iterator
Napoli
Roma
Firenze
Mestre

3.6.2 ListIterator listIterator()

Returns a ListIterator over the ArrayList. In contrast to Iterator, a ListIterator allows traversal in both directions. With this method, the ListIterator begins from the first element. It also provides methods for accessing the next and previous elements and also removing them. ListIterator also allows the addition of an element into the ArrayList. This interface is also part of the java.util package.

  • Parameters: none.
  • Returns: a ListIterator over the ArrayList.
    private static void listIteratorNoIndex() {
        /* create an ArrayList of Italian cities*/
        ArrayList<String> italianCities = new ArrayList<>();

        italianCities.add("Napoli");
        italianCities.add("Roma");
        italianCities.add("Firenze");
        italianCities.add("Mestre");

        System.out.println("Printing for \"listIteratorNoIndex\" method, the initial ArrayList of Italian cities printed without iterator");
        italianCities.stream().forEach(System.out::println);
        System.out.println();

        /* create a ListIterator over the ArrayList. This ListIterator starts from index = 0 */
        ListIterator italianCitiesIterator = italianCities.listIterator();

        /* printing the elements again, this time using our iterator*/
        System.out.println("Printing for \"listIteratorNoIndex\" method, the ArrayList of Italian cities printed with ListIterator, in forward order");

        /* hasNext() is used to check whether the iterator has reached the end of the ArrayList.
        *  Since the iterator is at the beginning of the ArrayList, hasPrevious() = false*/
        while(italianCitiesIterator.hasNext()) {

            /* next() return the next element of the ArrayList*/
            System.out.println(italianCitiesIterator.next());
        }
        System.out.println("\nPrinting for \"listIteratorNoIndex\" method, the ListIterator now is at the end of the ArrayList. We can print the ArrayList in reverse now.\n");

        /* printing the elements again, in reverse order, using our iterator*/
        System.out.println("Printing for \"listIteratorNoIndex\" method, the ArrayList of Italian cities printed with ListIterator, in reverse order");

        /* hasPrevious() is used to check whether the iterator has reached the beginning of the ArrayList*/
        while(italianCitiesIterator.hasPrevious()) {

            /* previous() return the previous element of the ArrayList*/
            System.out.println(italianCitiesIterator.previous());
        }
        System.out.println();
    }

Output

Printing for "listIteratorNoIndex" method, the initial ArrayList of Italian cities printed without iterator
Napoli
Roma
Firenze
Mestre

Printing for "listIteratorNoIndex" method, the ArrayList of Italian cities printed with ListIterator, in forward order
Napoli
Roma
Firenze
Mestre

Printing for "listIteratorNoIndex" method, the ListIterator now is at the end of the ArrayList. We can print the ArrayList in reverse now.

Printing for "listIteratorNoIndex" method, the ArrayList of Italian cities printed with ListIterator, in reverse order
Mestre
Firenze
Roma
Napoli

3.6.3 ListIterator listIterator(int index)

Returns a ListIterator over the ArrayList. With this method, the ListIterator begins at the specified index, unlike the method mentioned in the previous subsection.

  • Parameters: the specified index to begin iterating.
  • Returns: a ListIterator over the ArrayList.
    private static void listIteratorWithIndex() {
        /* create an ArrayList of Italian cities*/
        ArrayList<String> italianCities = new ArrayList<>();

        italianCities.add("Napoli");
        italianCities.add("Roma");
        italianCities.add("Firenze");
        italianCities.add("Mestre");

        System.out.println("Printing for \"listIteratorWithIndex\" method, the initial ArrayList of Italian cities printed without iterator");
        italianCities.stream().forEach(System.out::println);
        System.out.println();

        /* create a ListIterator over the ArrayList. This ListIterator starts from index = 2 */
        ListIterator italianCitiesIterator = italianCities.listIterator(2);

        /* printing the elements again, this time using our iterator*/
        System.out.println("Printing for \"listIteratorWithIndex\" method, the ArrayList of Italian cities printed with ListIterator, in forward order, starting from the 3rd city");

        while(italianCitiesIterator.hasNext()) {
            System.out.println(italianCitiesIterator.next());
        }
        System.out.println();
    }

Output

Printing for "listIteratorWithIndex" method, the initial ArrayList of Italian cities printed without iterator
Napoli
Roma
Firenze
Mestre

Printing for "listIteratorWithIndex" method, the ArrayList of Italian cities printed with ListIterator, in forward order, starting from the 3rd city
Firenze
Mestre

3.6.4 Spliterator spliterator()

Returns a Spliterator over the ArrayList. A Spliterator is an interface that traverses and partitions elements of some source. This interface is also part of the java.util package.

  • Parameters: none.
  • Returns: a Spliterator over the ArrayList.
    private static void spliterator() {
        /* create an ArrayList of Italian cities*/
        ArrayList<String> italianCities = new ArrayList<>();

        italianCities.add("Napoli");
        italianCities.add("Roma");
        italianCities.add("Firenze");
        italianCities.add("Mestre");

        System.out.println("Printing for \"spliterator\" method, the initial ArrayList of Italian cities printed without iterator");
        italianCities.stream().forEach(System.out::println);
        System.out.println();

        /* create a Spliterator over the ArrayList. This Spliterator starts from index = 0 */
        Spliterator italianCitiesIterator = italianCities.spliterator();

        /* printing the elements again, this time using our iterator*/
        System.out.println("Printing for \"spliterator\" method, the ArrayList of Italian cities printed with Spliterator");

        italianCitiesIterator.forEachRemaining(n -> System.out.println(n));

        System.out.println();
    }

Output

Printing for "spliterator" method, the initial ArrayList of Italian cities printed without iterator
Napoli
Roma
Firenze
Mestre

Printing for "spliterator" method, the ArrayList of Italian cities printed with Spliterator
Napoli
Roma
Firenze
Mestre

3.7 Miscellaneous Methods

3.7.1 void ensureCapacity(int minCapacity)

Ensures that the capacity of the ArrayList will be at least equal to the minimum capacity we provide. By providing a minimum capacity, we can be sure that there will be space for a large number of items. Remember that the items in an ArrayList are saved in sequential order. As a result, if we didn’t pre-allocate the space we might need and it turns out we need even more space, then we might lose CPU cycles, because of reallocation, making all operations slower.

You can imagine it like this: You want to buy a notebook to take notes, so you buy a 50-page notebook. But, It turns out you need more pages, so you buy a 100-page notebook. The problem is that you would like to have all your notes together, in one notebook. So in order to do that, you would have to copy all the notes from the 50-page notebook to the 100 one. This wouldn’t have happened if you had bought the 100-page notebook from the start. In the end, you would have lost time and effort, copying the same information to a larger collection.

  • Parameters: the minimum capacity to allocate for the ArrayList.
  • Returns: nothing.
    private static void ensureCapacity() {
        /* create an ArrayList of people invited to a party*/
        ArrayList<String> namesOfInvitedPeople = new ArrayList<>();

        namesOfInvitedPeople.add("Dimitris");
        namesOfInvitedPeople.add("Akis");
        namesOfInvitedPeople.add("Ignis");
        namesOfInvitedPeople.add("Katerina");

        System.out.println("Printing for \"ensureCapacity\" method, the initial ArrayList of people invited to a party");
        namesOfInvitedPeople.stream().forEach(System.out::println);
        System.out.println();

        namesOfInvitedPeople.ensureCapacity(50);

        System.out.println("Printing for \"ensureCapacity\" method, the capacity of the ArrayList has been increased to 50.\n" +
                "Its size doesn't change yet, so it's still equal to " + namesOfInvitedPeople.size());
        System.out.println();
    }

Output

Printing for "ensureCapacity" method, the initial ArrayList of people invited to a party
Dimitris
Akis
Ignis
Katerina

Printing for "ensureCapacity" method, the capacity of the ArrayList has been increased to 50.
Its size doesn't change yet, so it's still equal to 4

3.7.2 void forEach(Consumer action)

Applies the same Consumer action to all elements of the ArrayList. An action would be something along the lines of “multiply all numbers in the ArrayList by 10″ or “append a String after each element”.

  • Parameters: the Consumer action to be performed to each element.
  • Returns: nothing.
    private static void forEach() {
        /* create an ArrayList of people invited to a party*/
        ArrayList<String> namesOfInvitedPeople = new ArrayList<>();

        namesOfInvitedPeople.add("Dimitris");
        namesOfInvitedPeople.add("Akis");
        namesOfInvitedPeople.add("Ignis");
        namesOfInvitedPeople.add("Katerina");

        System.out.println("Printing for \"forEach\" method, the initial ArrayList of people invited to a party");
        namesOfInvitedPeople.stream().forEach(System.out::println);
        System.out.println();

        /* apply the same action for each name in the ArrayList. In our case, all people introduce themselves*/
        System.out.println("Printing for \"forEach\" method, the guests introduce themselves");
        namesOfInvitedPeople.forEach(personName -> System.out.println("My name is " + personName +". Nice to meet you!"));
        System.out.println();
    }

Output

Printing for "forEach" method, the initial ArrayList of people invited to a party
Dimitris
Akis
Ignis
Katerina

Printing for "forEach" method, the guests introduce themselves
My name is Dimitris. Nice to meet you!
My name is Akis. Nice to meet you!
My name is Ignis. Nice to meet you!
My name is Katerina. Nice to meet you!

3.7.3 void sort(Comparator c)

Sorts the ArrayList according to the provided Comparator.

  • Parameters: the Comparator which is used to determine the order of the elements for sorting.
  • Returns: nothing.
    private static void sort() {
        /* create an ArrayList of people invited to a party*/
        ArrayList<String> namesOfInvitedPeople = new ArrayList<>();

        namesOfInvitedPeople.add("Dimitris");
        namesOfInvitedPeople.add("Akis");
        namesOfInvitedPeople.add("Ignis");
        namesOfInvitedPeople.add("Katerina");

        System.out.println("Printing for \"sort\" method, the initial ArrayList of people invited to a party");
        namesOfInvitedPeople.stream().forEach(System.out::println);
        System.out.println();

        /* sort the people alphabetically, in reverse. reverseOrder() is a built-in Comparator*/
        namesOfInvitedPeople.sort(Collections.reverseOrder());

        /* print the result*/
        System.out.println("Printing for \"sort\" method, the guests are sorted alphabetically, in reverse order");
        namesOfInvitedPeople.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "sort" method, the initial ArrayList of people invited to a party
Dimitris
Akis
Ignis
Katerina

Printing for "sort" method, the guests are sorted alphabetically, in reverse order
Katerina
Ignis
Dimitris
Akis

3.7.4 void trimToSize()

Trims the ArrayList, removing any empty spaces which aren’t being used. From the outside, this change is not visible to us. On the other side, the change takes place internally, reducing the extra spaces which are not needed until we have as much space as we need.

In our notebook example, it would be like tearing of the extra blank pages, decreasing the notebook’s total pages as a result.

  • Parameters: none.
  • Returns: nothing.
    private static void trimToSize() {
        /* create an ArrayList of people invited to a party, expecting at least 50 people*/
        ArrayList<String> namesOfInvitedPeople = new ArrayList<>(50);

        namesOfInvitedPeople.add("Dimitris");
        namesOfInvitedPeople.add("Akis");
        namesOfInvitedPeople.add("Ignis");
        namesOfInvitedPeople.add("Katerina");

        System.out.println("Printing for \"trimToSize\" method, the initial ArrayList of people invited to a party");
        namesOfInvitedPeople.stream().forEach(System.out::println);
        System.out.println();

        /* trim the empty spaces of the ArrayList. This change is not visible to us; It's used for optimization*/
        namesOfInvitedPeople.trimToSize();

        /* print the result*/
        System.out.println("Printing for \"trimToSize\" method, after trimToSize() the number of guests is still " + namesOfInvitedPeople.size());
        namesOfInvitedPeople.stream().forEach(System.out::println);
        System.out.println();
    }

Output

Printing for "trimToSize" method, the initial ArrayList of people invited to a party
Dimitris
Akis
Ignis
Katerina

Printing for "trimToSize" method, after trimToSize() the number of guests is still 4
Dimitris
Akis
Ignis
Katerina

4. Conclusion

Hopefully, you are now able to fully take advantage of the powerful Java ArrayList. You can find the source code on our GitHub page.

5. Sources

[1]: ArrayList – Oracle

[2]: Object copying, “Shallow copy” section – Wikipedia

[3]: Iterator – Oracle

[4]: ListIterator – Oracle

[5] Spliterator, Oracle

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

Related Posts