The author selected Free and Open Source Fund to receive a donation as part of the Write for DOnations program.
List is a built-in interface from the Java package java.util
. Like arrays, lists allow you to group and store multiple elements in a collection. However, lists are more powerful and complex, providing advanced storage options and retrieving values.
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:
LinkedList
is designed differently with a higher initialization cost regarding resources but more optimal for manipulating data.Vector
is 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.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:
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.
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: 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 a String
type 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.pets
is the name of the list.new ArrayList<>()
means that you are creating a new object of type ArrayList
. Here you can specify again that the list will hold String
objects 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:
Outputpets ==> []
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.
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:
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:
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:
Outputjshell> 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.
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:
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.
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
MethodThe 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
MethodYou 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
MethodYou 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:
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
MethodThe 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:
Output[Dog, Fox]
Note that the animals may differ depending on which ones you have added.
forEach
MethodThe 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.
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java is a mature and well-designed programming language with a wide range of uses. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!