Java Lists

Lists, like arrays, can contain multiple values of the same type, however they are a lot more flexible than arrays, due to the ease of adding and removing values. Unlike with arrays, the number of values in a list does not have to be specified when it is defined. In Java there are two general purpose types of list, array lists and linked lists, the first of which will be discussed here.

The example below creates a list of strings called ‘names’, adds three names, then, using a ‘foreach’ loop, displays the names in the console. Note that, in order for this example to work both ‘java.util.ArrayList’ and ‘java.util.List’ need to be imported.

List<String> names = new ArrayList<>();

names.add("George");
names.add("Bob");
names.add("Fred");

for (String name : names)
{
   System.out.println(name);
}

The output from this will be as follows.

George
Bob
Fred

An alternative way to initialise the list is to use the ‘Collections’ ‘addAll’ method. This needs an additional import, ‘java.util.Collections’.

List<String> names = new ArrayList<>();
Collections.addAll(names,
       "George",
       "Bob",
       "Fred");

Note that, like with an array, an ordinary ‘for’ loop could be used, but a ‘foreach’ loop is simpler.

In order to add another name to the list it is just a case of repeating how “George”, “Bob” and “Fred” were added in the first example above.

names.add("Andrew");

As with an array, each item in a list has a corresponding index value, starting at zero for the first item. This index can be used to add an item to a list at a specific position, for example, the name ‘James’ could be added to the above list between ‘George’ and ‘Bob’.

names.add(1, "James");

If the names were output to the console now using the above method the output would be as follows.

George
James
Bob
Fred
Andrew

Items from a list can also be removed in a similar fashion to adding.

names.remove("Andrew");

As well as being able to remove a list item by its value, it is also possible to use the index. To remove the name ‘James’, which was added earlier, the index number one could be used.

names.remove(1);

If it is required, either for display or processing purposes, to have the items in a list in order, this can be achieved by importing ‘java.util.Collections’. A list can be ordered both in ascending and descending order.

// Ascending order.
Collections.sort(names);

// Descending order.
Collections.reverse(names);