Sub topic 14
Choosing Between Arrays and Collections
Java gives you more than one way to hold a group of values. Two common choices are arrays and lists.
An array has a fixed number of positions. A list is an ordered group of elements that may be able to grow or shrink. Both let you find an element by its index, which is its position number.
The best choice depends on what the program needs to do with the group. This chapter compares the choices and shows how to move between them.
What is a collection?
A collection is an object that groups elements. Java provides several kinds of collections. For example, a set is a collection that does not allow duplicate elements.
A list keeps elements in order and allows duplicates. Its indexes start at zero, just like array indexes.
An array is also an object, but it is not a Java collection. One useful difference is that an array can hold primitive values, such as int values, directly. A primitive value is a basic value such as a number or a true-or-false value.
Fixed size or changing size?
An array’s length is fixed when you create it. You can change an element, but you cannot add a new position to the same array.
For example, an array can be a good fit for one reading from each day of a seven-day week. The number of positions is known.
An ArrayList can grow and shrink. It is a good fit for a waiting list when people may join or leave. ArrayList is a class: a Java definition used to create objects.
If you need a larger array, you can create a new one and copy values into it. That does not change the length of the original array. Other variables that refer to the original still refer to that original array.
A side-by-side example
The following program uses an array for three known readings. It uses an ArrayList for a group of readings that can change.
Save it as ArrayAndListDemo.java.
import java.util.ArrayList;
import java.util.List;
public class ArrayAndListDemo {
public static void main(String[] args) {
int[] fixedReadings = {18, 21, 24};
fixedReadings[1] = 22;
System.out.println("Array length: " + fixedReadings.length);
System.out.println("Second array reading: " + fixedReadings[1]);
List<Integer> changingReadings = new ArrayList<>();
changingReadings.add(18);
changingReadings.add(21);
changingReadings.add(24);
changingReadings.set(1, 22);
changingReadings.add(26);
System.out.println("List size: " + changingReadings.size());
System.out.println("Second list reading: " + changingReadings.get(1));
System.out.println("List: " + changingReadings);
}
}Run it with:
javac ArrayAndListDemo.java
java ArrayAndListDemoThe output is:
Array length: 3
Second array reading: 22
List size: 4
Second list reading: 22
List: [18, 22, 24, 26]The array still has three positions after the program changes its second value. The list has four elements after the program calls add.
List is an interface: a description of operations that a kind of object provides. ArrayList is one class that provides those operations. The declaration uses List so that the rest of the code can work with the list through those operations.
The import lines make the names List and ArrayList available in the program. They are part of Java’s standard library, which is a group of useful classes and interfaces supplied with Java.
Common operations
The two choices use different ways to perform similar tasks.
| Task | Array | `ArrayList` |
|---|---|---|
| Find the number of elements | `values.length` | `values.size()` |
| Read the first element | `values[0]` | `values.get(0)` |
| Replace the first element | `values[0] = 10` | `values.set(0, 10)` |
| Add an element at the end | Create a new array | `values.add(10)` |
| Remove an element | Create a new array if the size must shrink | `values.remove(0)` removes the element at index zero |
Reading or changing an element by index is usually quick for both arrays and ArrayList. An index must still be within the current range. Trying to read index 3 from a group of three elements causes an error because the valid indexes are 0, 1, and 2.
Removing or inserting an element near the start of an ArrayList can take more work. The list must shift later elements to keep them in order. Adding at the end is usually quick, though an occasional addition takes more work when the list needs more room.
An ArrayList uses an array internally to hold its elements. When it needs more room, it can create a larger internal array and move the elements there. Your code can keep using the same ArrayList object.
Removing a number from a list
Be careful when removing from a list of numbers. For a List<Integer>, remove(1) removes the element at index 1, not necessarily the number 1.
To remove the number 1 by value, use remove(Integer.valueOf(1)). If the list contains that value more than once, this removes its first occurrence.
Primitive values and list elements
An array can hold primitive values directly:
int[] counts = {2, 4, 6};A list cannot use a primitive type such as int between its angle brackets. Instead, use Integer:
List<Integer> counts = new ArrayList<>();Integer is a wrapper class: an object type that holds an int value. The angle brackets specify the kind of element the list holds. This feature is called generics.
Java usually converts between int and Integer for you. For example, counts.add(2) puts an Integer in the list. This automatic conversion is called boxing.
A wrapper value can also be null, meaning that it refers to no object. A primitive int cannot be null. If Java tries to turn a null Integer into an int, the program throws a NullPointerException, which is a runtime error.
Arrays of primitives can use less memory than lists of wrapper objects. The exact difference depends on the data and the Java runtime. If memory or speed is important, measure your program with realistic data rather than choosing from a general rule alone.
Choosing a type for a method
A method is a named piece of code that can receive values and return a result. When a method needs a group of values, choose a type that matches what it needs.
- Use an array when the method expects a fixed-size group or must work with primitive values directly.
- Use
Listwhen the method needs list operations but does not need a particular list class. - Use
ArrayListwhen the method specifically needs that class. This is less common.
For example, a method that reads names by index can often accept a List<String>. The caller can then supply an ArrayList or another suitable kind of list.
A List type alone does not promise that the list can grow. Some lists have a fixed size, and some do not allow changes at all. If a method needs to add elements, make that requirement clear.
Converting between an array and a list
Sometimes an existing method needs an array while your code uses a list, or the other way around. Java provides ways to convert between them.
The next program starts with an array of names. It creates a fixed-size list backed by that array, then creates a separate ArrayList.
Save it as ConversionDemo.java.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConversionDemo {
public static void main(String[] args) {
String[] names = {"Ada", "Lin"};
List<String> view = Arrays.asList(names);
view.set(0, "Mina");
System.out.println("Array after changing view: "
+ Arrays.toString(names));
List<String> flexibleNames = new ArrayList<>(view);
flexibleNames.add("Sam");
System.out.println("Flexible list: " + flexibleNames);
String[] result = flexibleNames.toArray(new String[0]);
System.out.println("New array: " + Arrays.toString(result));
}
}Run it with:
javac ConversionDemo.java
java ConversionDemoThe output is:
Array after changing view: [Mina, Lin]
Flexible list: [Mina, Lin, Sam]
New array: [Mina, Lin, Sam]Arrays.asList(names) creates a list view: a list connected to the existing array. Changing an element through the view changes that array element too. The view has a fixed size, so calling add or removing an element from it causes an error.
new ArrayList<>(view) creates a separate list that can grow and shrink. Changing its size does not change the array’s size. The list initially holds the same element references as the view; it does not create new copies of the objects in those positions.
toArray(new String[0]) creates a separate String array containing the list’s elements.
A decision guide
| Situation | Good starting choice | Reason |
|---|---|---|
| The number of values is known and stays fixed | Array | Its fixed length matches the task |
| Values must often be added or removed at the end | `ArrayList` | It manages changes in size |
| A method only needs general list operations | `List` as the parameter type | Callers can use a suitable list class |
| A method requires an array | Array | It matches the required type |
| A large group holds primitive numbers | Consider an array | It stores primitive values directly |
These are starting points, not absolute rules. Consider how the group will change, what its users need, and whether the code is easy to understand.
Exercise
A program records the names of people joining a queue. The number of people is not known in advance, and new people join throughout the day. Would an array or an ArrayList be a simpler starting choice? Why?
Show answer
An ArrayList is a simpler starting choice because it can grow as people join. An array has a fixed length, so the program would need a new array when it runs out of positions.
Exercise
A list is created with Arrays.asList(names), where names is a String array. What happens if you change an element with set? Can you add another element?
Show answer
The change also appears in the names array because the list is backed by that array. The list has a fixed size, so adding an element causes an error.