Creating ArrayLists


Creating ArrayLists

🙋 Need help? Ask an expert now!

Now that we have entered the world of arrays, let's talk about the ArrayList class in Java and what it offers in addition to the known capabilities of arrays. An ArrayList object contains an array of object references as well as methods for managing the array. The elements of an ArrayList must be object references, not primitive data such as int or double. Take a look at the ArrayList of String values as an example. The ArrayList class has to be imported from the java.util package in order for the program to compile without error.
package exlcode;

import java.util.ArrayList;

public class ArrayListsExample {

  public static ArrayList exampleVariableOne = new ArrayList();
  public static ArrayList exampleVariableTwo = new ArrayList(5);

  public static void main(String[] args) {
    // "add" will be explained later this unit
    // ArrayLists can be printed directly to the console, unlike arrays

The syntax for declaring an ArrayList is:

ArrayList<objectType> name = new ArrayList<objectType>();.

By default, an ArrayList will start out with 10 empty cells. If you want to start with an initial capacity, put a number in the parentheses. This does not limit the size the ArrayList can expand to. A benefit of an ArrayList is that elements may continue to be added regardless of the original size of the ArrayList. The size of the ArrayList will automatically increase and no information will be lost.

Edit Me on GitHub!

Application Question

Which of the following is a logical reason to use an ArrayList instead of an array?