In Java, the standard array holds a fixed number of values of the same type. That means that once an array is created, developers cannot change its size. Meanwhile, Java’s Arraylist class offers a resizable array, whose contents can be modified at any time without having to create a whole new array. Beyond that, the ArrayList class has many useful methods which makes working with arrays much easier. This programming tutorial will cover everything you need to know to work with ArrayLists as well as present some reasons to choose it over the regular array type.
Read: Top Online Courses to Learn Java
Java ArrayList Basics
The ArrayList is part of the Java collection framework and is located in the java.util package. It implements the List interface, which provides the dynamic sizing functionality. While a little slower than the standard array, the ArrayList offers a lot of features that you will not find in a standard array.
How to Create an ArrayList in Java
To create an ArrayList, be sure to import the java.util.ArrayList package first. Then, all you need to do is invoke its constructor:
import java.util.ArrayList; ArrayList<String> guitars = new ArrayList<String>();
ArrayList supports generics, which helps enforce type safety. Programmers can create an ArrayList of any type, from simple types like Integer, String, and Double to complex types like HashMaps or any user defined objects.
Adding and Removing Items from an ArrayList in Java
You can add values to an ArrayList by using the add(obj) method, which will add the object to the end of the list. Meanwhile, the add(index,obj) method adds the object at the passed index, but first moves over any existing values to higher indicies to make room for the new object. Note that, like regular arrays, indexes are zero-based.
You can also remove values from an ArrayList by using remove(index), which removes the item at the given index from the list. This will shift over all the other items over in the underlying array by one ordinal position and decrease the size of the ArrayList by 1.
The following program showcases the add and remove methods by adding some guitars to a new ArrayList, including one at a specific index. The first item in the list is then removed:
import java.util.ArrayList; ArrayList<String> guitars = new ArrayList<String>(); guitars.add("Fender"); guitars.add("Gibson"); guitars.add("Jackson"); System.out.println(guitars); // Inserts new item in 2nd position guitars.add(1, "Washburn"); System.out.println(guitars); // Removes 1st element guitars.remove(0); System.out.println(guitars);
We can see the full program output below:
Read: How to Print an Array in Java
Java ArrayList get and set Methods
Once you have got some items in your ArrayList, developers will want to access them to either read or modify their values. In contrast to the square brackets – array[index] – employed by arrays, ArrayLists provide access to the underlying array via methods. You can get the object at an index using obj = listName.get(index)
and set the object at an index using listName.set(index,obj)
. Here is a Java code example that builds on the previous one:
// Print the 3rd element of the list System.out.println(guitars.get(2)); guitars.set(2, "Yamaha"); // Jackson is now Yamaha System.out.println(guitars);
Here is the updated program output, with the two new sysouts highlighted in red:
Read: Using ArrayList versus Hashmap in Java
How to Get the Size of an ArrayList in Java
Unlike arrays, which have the length property, ArrayLists provide the size() method to get the number of items in the ArrayList. Hence, we could obtain the length of the guitars ArrayList by invoking its size() method:
guitars.set(2, "Yamaha"); // Jackson is now Yamaha System.out.println(guitars); // Prints 3 System.out.println(guitars.size());
Sorting an ArrayList in Java
ArrayLists commonly need to be sorted for display purposes, which can easily be done using either the Collections.sort() or ArrayList.sort() method.
The Collections.sort() method is used to sort the elements of the specified list in ascending order. It is quite similar to the Arrays.sort() method but is more versatile as it can sort the elements of an array as well as a linked list, queue and many other types that extend Collections, including ArrayList.
Keep in mind that Collections.sort() mutates the original list, so you will want to call it on its own line, before accessing the sorted list, as in the following example:
An alternative way to sort an ArrayList is to use its own instance sort method. It differs somewhat from Collections.sort() in that the ArrayList’s sort() method accepts a comparator method as a parameter (it’s optional for Collections.sort()). The comparator specifies the sorting order of the ArrayList and is especially useful for sorting custom objects. That being said, comparators work equally well on simple types like Strings and Integers:
import java.util.ArrayList; import java.util.Comparator; public class Main { public static void main(String[] args) { ArrayList<String> guitars = new ArrayList<>(); guitars.add("Gibson"); guitars.add("Yamaha"); guitars.add("Fender"); guitars.add("Jackson"); System.out.println("guitars before sorting: " + guitars); // Sort an ArrayList using a Comparator guitars.sort(new Comparator<String>() { @Override public int compare(String guitar1, String guitar2) { return guitar1.compareTo(guitar2); } }); // The above sort() method can also be written using a lambda expression guitars.sort((guitar1, guitar2) -> guitar1.compareTo(guitar2)); // An even more concise solution! guitars.sort(Comparator.naturalOrder()); System.out.println("guitars after sorting: " + guitars); } }
Using a comparator function is probably overkill for such a straight-forward sort, but, as the results show, it certainly worked:
Final Thoughts on the Java Arraylist Class
While vanilla arrays are perfectly fine for holding a fixed number of values of the same type, consider moving up to an ArrayList if you need dynamic sizing or think that you might benefit from its many useful methods.
Read: Java Tools to Increase Productivity