Created: 2023-08-27 17:11
Status: #concept
Subject: Programming
Tags: Java java.util Linked List Java Arrays java.util.Collection

java.util.ArrayList

It is a java.util.* class that is a dynamically-sized array which we can import in order to use the new ArrayList<T>(int size | Collection<T> arr).

// import the list so the program can use it
import java.util.ArrayList;

public class Program {

    public static void main(String[] args) {
        // create a list
        ArrayList<String> wordList = new ArrayList<>();

        wordList.add("First");  // add to the last index, 0
        wordList.add("Second"); // add to the last index, 1

        System.out.println(wordList.get(1)); // "Second"
    }
}
They are useful because they only store Java Class object instance Reference Types instead of Value Types.

Common Methods

Consumer Methods

A Consumer is a function that takes a single value and returns void.

  • we can use a Java Anonymous Function (...args) -> { ... }.

import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
        // create an ArrayList which going to
        // contains a list of Numbers
        ArrayList<Integer> Numbers = new ArrayList<Integer>();
  
        // Add Number to list
        Numbers.add(23);
        Numbers.add(32);
        Numbers.add(45);
        Numbers.add(63);
  
        // forEach method of ArrayList and
        // print numbers
        Numbers.forEach((n) -> System.out.println(n));
    }
}

Automatic Type Generic Inference

When we are instantiating a new ArrayList<T>(), we can omit T if the variable that is being assigned the new ArrayList<>() is already declared.

When we do ArrayList<String> names = new ArrayList<>();, the assigned list will be of type String.

public class AmusementParkRide {
    private String name;
    private int minimumHeigth;
    private int visitors;
    private ArrayList<Person> riding;

    public AmusementParkRide(String name, int minimumHeigth) {
        this.name = name;
        this.minimumHeigth = minimumHeigth;
        this.visitors = 0;
        this.riding = new ArrayList<>();
    }

    // ..
}

References