Table of Contents
*The author selected Free and Open Source Fund to receive a donation as part of the Write for DOnations program.*
Introduction
One key difference with arrays is that you can store only objects in lists. Thus, you cannot store a primitive type directly in a list, but instead you have to use its wrapper class. Since a list is an interface in Java, it has different implementations. In this tutorial you will be using the ArrayList implementation class, also part of the built-in java.util package. ArrayList is commonly used because it is fast and lightweight. Still, the same code examples and principles should work if you choose another implementation.
Other implementations of the List interface are:
LinkedListis designed differently with a higher initialization cost regarding resources but more optimal for manipulating data.Vectoris synchronized, i.e., it is safe to be used in multi-threaded programs. However, synchronization comes with a performance cost on each operation for manipulating data, and that's why it should be used only when needed.
Prerequisites
To follow this tutorial, you will need:
- An environment in which you can execute Java programs to follow along with the examples. To set this up on your local machine, you will need the following:
- Java (version 11 or above) installed on your machine, with the compiler provided by the Java Development Kit (JDK). For Ubuntu and Debian, follow the steps for Option 1 in our tutorial How To Install Java with Apt on Ubuntu 22.04. For other operating systems, including Mac and Windows, follow the download options for Java installation.
- To compile and run the code examples, this tutorial uses Java Shell, which is a *Read-Evaluate-Print Loop* (REPL) run from the command line. To get started with JShell, check out the Introduction to JShell guide. All examples are executed in one JShell session to avoid redundant instructions and use the same variables.
- Familiarity with Java and object-oriented programming, which you can find in our tutorial How To Write Your First Program in Java.
- An understanding of Java data types is discussed in our tutorial Understanding Data Types in Java.
Creating lists
To create a list, you must declare it and initialize its implementation. In the following example, you will create a list using the ArrayList implementation and containing String objects. Open jshell and type:
[info] Info: To follow the example code in this tutorial, open the Java Shell tool on your local system by running the jshell command. Then you can copy, paste, or edit the examples by adding them after the jshell> prompt and pressing ENTER. To exit jshell, type /exit.
List<String> pets = new ArrayList<>();
The line above contains the following important parts:
List<String>means the object will be a list. The diamond<>operator is used to specify that the list object should be created with aStringtype argument. Specifying the type of arguments when creating a list is good practice. Otherwise, you risk trying to insert an object that cannot be cast, i.e., automatically converted, resulting in an error.petsis the name of the list.new ArrayList<>()means that you are creating a new object of typeArrayList. Here you can specify again that the list will holdStringobjects inside its diamond operator, but it's not necessary because you have already specified it once in the beginning of the line.
The output from the jshell command above will be a confirmation that an empty pets lists has been created:
[secondary_label Output]
pets ==> []
You might have noticed that when you created the pets list, you didn't have to specify its size. The size of the list is dynamically taken care of by Java, and this gives you more flexibility when you don't know beforehand the number of elements you will be storing in the list.
Adding List Elements
Once a list is created, you can start adding elements to it. You have options to add a single element or a collection of elements at once. Furthermore, each of the two options has an optional parameter to specify at which position in the list you want to start the addition. Here are some examples.
The simplest list operation is to add a single element to your pets, let's say a dog, like this:
pets.add("Dog");
When you run the above in jshell you will see the following output:
[secondary_label Output]
$4 ==> true
You can disregard $4 here and throughout the tutorial as it is a temporary variable used by jshell. What matters is true which is a confirmation that Dog has been successfully added to your list. In contrast, if you try to add an object other than String, you will get an error. For example, try adding 1 to the list like this:
pets.add(1);
You will see the following error:
[secondary_label Output]
| Error:
| incompatible types: int cannot be converted to java.lang.String
| pets.add(1);
| ^
The error is very clear. The pets list should be used only for String objects and a primitive 1 cannot be directly converted to a String. Because of this error, 1 is not added to the list.
Next, try to add another pet to your pet and let it be a valid value, such as a cat. However, out of concern for your cat's ego, you may want to place the cat before the dog on the list. To do this, you can specify a parameter for the index at which the cat should be added like this:
pets.add(0, "Cat");
The indices of all lists begin at 0. That's why you specify 0 when you want an element to be added at the first position. Thus, your cat will be the first in your pet's list.
To confirm your cat is before your dog in the list, you can enter the name of the list pets in jshell and expect the following output:
[secondary_label Output]
jshell> pets
pets ==> [Cat, Dog]
You can also add multiple entries simultaneously using the method addAll. This method works similarly to add. If you pass one argument, it has to be a collection such as ArrayList. Optionally, you can pass two arguments. The first one then should be the index at which the elements are to be added; the second one should contain the new elements lists. As an exercise, add a new list containing more animals to the pets list using the addAll method.
Altering List Elements
You can alter a list element using the set method and passing two arguments. The first argument is the index, and the second is the value. For example, to restore the dog in front of the list, run the following code:
pets.set(0, "Dog")
When you set Dog at the beginning of the pets list, you practically replace the previous Cat value.
Now your list has two dogs in it and maybe you want to remove one. This can be done with the remove method like this:
pets.remove("Dog")
When you execute the above code in jshell, you will see output such as:
[secondary_label Output]
$9 ==> true
The true statement confirms that your operation has succeeded, i.e. that there has been a value Dog and it has been removed. If you try to remove a cat from the list, you will not receive such a confirmation. Instead, you will see false printed because no such element has been found, nor removed.
Finally, if you want to remove all the list elements, you can do so by using the clear method like this:
pets.clear()
After completing the above execution, your pets list will be empty, and you can start adding elements again starting from index 0.
Using Additional List Methods
So far, you have already used some of the most popular list methods such as add(), set(), and remove(). In addition to those mentioned, the List interface includes several other useful methods that can improve the efficiency and accuracy of your code. Below are some of the most significant:
equals Method
The equals method compares two lists to determine their equal. For the lists to be equal, they must be of the same type, size, and corresponding elements. As an example, create two lists with pets – current and desired:
List<String> currentPets = new ArrayList<>();
List<String> desiredPets = new ArrayList<>();
Add a dog element to both lists like this:
currentPets.add("Dog");
desiredPets.add("Dog");
Now you can compare them:
currentPets.equals(desiredPets)
You will get a true response confirming both lists are equal. However, try to add a new element, such as a snake, to the desired pets:
desiredPets.add("Snake")
After that compare the two lists again:
currentPets.equals(desiredPets)
This time you will get a false response because the two lists are not equal.
contains Method
You can search a list for a specific value with the contains method. For example, to check whether the desiredPets list contains a snake, you can write:
desiredPets.contains("Snake")
The output from the above command will print true, thus confirming that there is a snake in the desired pets list.
indexOf Method
You can use the indexOf method to find the position of an item in the list. For example, to find out the position of the dog in the pets list, you can execute:
pets.indexOf("Dog")
The output will show a temporary variable pointing to the position of the item:
[secondary_label Output]
$31 ==> 0
The output indicates that the value for Dog has an index of 0, making it the first item in the list. This information can be helpful if you need to use or replace this value.
toString Method
The toString method allows you to retrieve all the elements of a list as a single String, i.e. plain text. This is very useful for debugging or logging purposes. To see how it works, use the method System.out.println for printing output to the console and run in jshell the following command:
System.out.println(pets.toString())
This will print nicely each of your animals in the following format:
[secondary_label Output]
[Dog, Fox]
Note that the animals may differ depending on which ones you have added.
forEach Method
The foreach method allows you to iterate through all the elements of the list and execute an action with each of them. This method is an alternative to writing your own foreach loop. The foreach method accepts a Consumer object as an argument. Consumers will be covered in a later tutorial, and a good example will require additional explanation outside the current scope. Still, if you are curious, try to devise your example for the foreach method.
Conclusion
In this tutorial, you learned how to work with Java lists and, more specifically, the ArrayList implementation. You created a list, viewed its elements, and emptied it. You also learned best practices and useful methods for working with lists.
For more on Java, check out our How To Code in Java series.