Table of contents:

  1. Creating a list
  2. Defining the Type of Values That a List Can Contain
  3. Adding to a List and Retrieving a Value from a Specific Place

Creating a list

Creating a new list is done with the command ArrayList list = new ArrayList<>(), where Type is the type of the values to be stored in the list (e.g. String).

import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {
        // create a list
        ArrayList<String> list = new ArrayList<>();
        // the list isn't used yet

The type of the ArrayList variable is ArrayList. When a list variable is initialized, the type of the values to be stored is also defined in addition to the variable type — all the variables stored in a given list are of the same type. As such, the type of an ArrayList that stores strings is ArrayList<String>. A new list is created with the command new ArrayList<>();.

Defining the Type of Values That a List Can Contain

ArrayList<Integer> list = new ArrayList<>();

ArrayList<Boolean> list = new ArrayList<>();

ArrayList<String> list = new ArrayList<>();
list.add("Some text");

Once a list has been created, ArrayList assumes that all the variables contained in it are reference types. Java automatically converts an int variable into Integer when one is added to a list, and the same occurs when a variable is retrieved from a list. The same conversion occurs for double-type variables, which are converted to Double. This means that even though a list is defined to contain Integer-type variables, variables of type int can also be added to it.

ArrayList<Integer> integers = new ArrayList<>();
int integer = 1;

ArrayList<Double> doubles = new ArrayList<>();
double d = 3.3;

Adding to a List and Retrieving a Value from a Specific Place

Addition is done with the list method add, which takes the value to be added as a parameter. We then print the value at position zero. To retrieve a value from a certain position, you use the list method get, which is given the place of retrieval as a parameter.

To call a list method you first write the name of the variable describing the list, followed by a dot and the name of the method.

  public static void main(String[] args) {
        // create the word list for storing strings
        ArrayList<String> wordList = new ArrayList<>();

        // add two values to the word list

        // retrieve the value from position 0 of the word list, and print it

As can be seen, the get method retrieves the first value from the list when it is given the parameter 0. This is because list positions are counted starting from zero. The first value is found by wordList.get(0), the second by wordList.get(1), and so on.

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee