Table of contents:
- Creating a list
- Defining the Type of Values That a List Can Contain
- 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
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
Defining the Type of Values That a List Can Contain
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.
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.
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.