Java offers both basic built-in arrays and also an ArrayList class. The more basic arrays come from Java's C heritage. When creating an array, the size must be specified and can never be changed:
// create an array of 100 integers
int[] array = new int[100];
ArrayLists on the other hand start out empty and can grow dynamically as the program runs. The ArrayList class also contains helpful methods. In this class, we'll use ArrayList almost all of the time.
An ArrayList of Strings can be declared as follows:
ArrayList<String> names = new ArrayList<>();
The type should be indicated inside the angled brackets. It's possible to leave this off, but then the list could store any type of data whatsoever. By specifying the type we let the compiler help us make sure only the right sort of thing goes into the list.
The second pair of angled brackets can also have the type in it again:
ArrayList<String> names = new ArrayList<String>();
This line does the same thing as the one previous. The angled brackets do need to be there one way or another. Leaving the type off is less typing, so that's the approach taken here.
Each of these two lines declare and also initialize and ArrayList. An ArrayList cannot be used if it's not declared. The compiler will let you run your program if you forget to initialize the list. But objects must be initialized before they are used. This code will crash, for instance:
ArrayList<String> names;
names.add("Alice");
Another complication in creating ArrayLists is that they cannot be
created for the primitive Java types such as int
,
float
, boolean
and so on. This is because
Java's generic system is based on Object types alone.
Wrapper classes exist for all the primitive types to get around this limitation. To make and ArrayList of ints, instead do:
ArrayList<Integer> names = new ArrayList<>();
One of the benefits of using ArrayLists is the amount of methods the class has for modifying and working with the list. The Javadocs page for ArrayList lists them all in detail.
Probably the most commonly used ones are:
add
This method takes an item to add to the list as a parameter. By default it appends to the end of the list. You can also pass a second parameter which is the index you want the item to be inserted at, instead of the end.
get
This method takes an index and returns to you the item stored at that location
in the list. If the index you pass is not valid, it throws an
IndexOutOfBoundsException
.
remove
You can call this method with two different types of parameters. If you pass an integer, it will remove the item from that index in the list. If you pass the type your list is storing, it will remove the first object in the list with a matching value.
size
Returns the number of items actually stored in the list.
clear
Removes all elements from the list.
indexOf
This method takes an object of the type being stored in the list as its parameter. It returns to us the index of the first matching item in the list. This allows us to search the list for data. If the item is not found, -1 is returned instead.
There are two main ways to loop through an ArrayList. The first is the older, C-style for loop:
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
This works by keeping a counter variable, i
, as an index
into the list. It starts at 0 and keeps going while it's less than the
size of the list. This variable is then passed into the get()
method to retrieve each item from the list.
There is also the newer "foreach" style for loop, reminiscent of Python's for loop:
for (String name : names) {
System.out.println(name);
}
The benefit of this is that it is shorter and less error-prone. For instance, you can't get an off-by-one error with your index with this style for loop. The downside is that we don't have an index variable. So if we need to know which element we're on we'd need to use the first style loop.
One thing we will often want to do with ArrayLists is to call a method on
each object being stored in the list. For instance, let's say we have a
Student
class which has a method called printReport()
.
We can make an ArrayList of Student objects like this:
ArrayList<Student> students = new ArrayList<>();
How then could we call the method we want? Some beginner programmers attempt
to call printReport()
on the ArrayList, like this:
students.printReport();
However, this will not work because students
is not a Student
object, it's an ArrayList object. And ArrayList does not have any method
called printReport
. So instead we need to get at the individual
students stored in the list, by using a loop:
for (Student s : students) {
s.printReport();
}
Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.