An ArrayList object can be used to store a list of objects. Now we are ready to introduce a very useful class for storing objects. You can create an array to store objects. But, once the array is created, its size is fixed. Java provides the ArrayList class, which can be used to store an unlimited number of objects. Figure below shows some methods in ArrayList.
ArrayList is known as a generic class with a generic type E. You can specify a concrete type to replace E when creating an ArrayList. For example, the following statement creates an ArrayList and assigns its reference to variable cities. This ArrayList object can be used to store strings.
ArrayList<String> cities = new ArrayList<String>();
The following statement creates an ArrayList and assigns its reference to variable dates. This ArrayList object can be used to store dates.
ArrayList<java.util.Date> dates = new ArrayList<java.util.Date> ();
The statement
ArrayList<AConcreteType> list = new ArrayList<AConcreteType>();
can be simplified by
ArrayList<AConcreteType> list = new ArrayList<>();
The concrete type is no longer required in the constructor thanks to a feature called type inference. The compiler is able to infer the type from the variable declaration.
The program below gives an example of using ArrayList to store objects.
package demo;
import java.util.ArrayList;
public class TestArrayList {
public static void main(String[] args) {
// Create a list to store cities
ArrayList<String> cityList = new ArrayList<>();
// Add some cities in the list
cityList.add("London");
// cityList now contains [London]
cityList.add("Denver");
// cityList now contains [London. Denver]
cityList.add("Paris");
// cityList now contains [London, Denver, Paris]
cityList.add("Miami");
// cityList now contains [London, Denver, Paris, Miami]
cityList.add("Seoul");
// cityList now contains [London, Denver, Paris, Miami, Seoul]
cityList.add("Tokyo");
// cityList now contains [London, Denver, Paris, Miami, Seoul, Tokyo]
System.out.println("List size? " + cityList.size());
System.out.println("Is Miami in the list? " + cityList.contains("Miami"));
System.out.println("The location of Denver in the list? " + cityList.indexOf("Denver"));
System.out.println("Is the list empty? " + cityList.isEmpty()); // Print false
// Insert a new city at index 2
cityList.add(2, "Xian");
// Contains [London, Denver, Xian, Paris, Miami, Seoul, Tokyo]
// Remove a city from the list
cityList.remove("Miami");
// Contains [London, Denver, Xian, Paris, Seoul, Tokyo]
// Remove a city at index 1
cityList.remove(1);
// Contains [London, Xian, Paris, Seoul, Tokyo]
// Display the contents in the list
System.out.println(cityList.toString());
// Display the contents in the list in reverse order
for(int i = cityList.size() - 1; i >= 0; i--)
System.out.print(cityList.get(i) + " ");
System.out.println();
// Create a list to store two circles
ArrayList<CircleFromSimpleGeometricObject> list = new ArrayList<>();
// Add two circles
list.add(new CircleFromSimpleGeometricObject(2));
list.add(new CircleFromSimpleGeometricObject(3));
// Display the area of the first circle in the list
System.out.println("The area of the circle? " + list.get(0).getArea());
}
}
List size? 6
Is Miami in the list? True
The location of Denver in the list? 1
Is the list empty? false
[London, Xian, Paris, Seoul, Tokyo]
Tokyo Seoul Paris Xian London
The area of the circle? 12.566370614359172
Since the ArrayList is in the java.util package, it is imported in line 2. The program creates an ArrayList of strings using its no-arg constructor and assigns the reference to cityList (line 8). The add method (lines 11–21) adds strings to the end of list. So, after
cityList.add("London") (line 11), the list contains
[London]
After cityList.add("Denver") (line 13), the list contains
[London, Denver]
After adding Paris, Miami, Seoul, and Tokyo (lines 15–21), the list contains
[London, Denver, Paris, Miami, Seoul, Tokyo]
Invoking size() (line 24) returns the size of the list, which is currently 6. Invoking contains("Miami") (line 25) checks whether the object is in the list. In this case, it returns true, since Miami is in the list. Invoking indexOf("Denver") (line 26) returns the index of Denver in the list, which is 1. If Denver were not in the list, it would return -1. The isEmpty() method (line 27) checks whether the list is empty. It returns false, since the list is not empty.
The statement cityList.add(2, "Xian") (line 30) inserts an object into the list at the specified index. After this statement, the list becomes
[London, Denver, Xian, Paris, Miami, Seoul, Tokyo]
The statement cityList.remove("Miami") (line 34) removes the object from the list. After this statement, the list becomes
[London, Denver, Xian, Paris, Seoul, Tokyo]
The statement cityList.remove(1) (line 38) removes the object at the specified index from the list. After this statement, the list becomes
[London, Xian, Paris, Seoul, Tokyo]
The statement in line 42 is same as
System.out.println(cityList);
The toString() method returns a string representation of the list in the form of [e0.toString(), e1.toString(), ..., ek.toString()], where e0, e1, . . . , and ek are the elements in the list.
The get(index) method (line 46) returns the object at the specified index.
ArrayList objects can be used like arrays, but there are many differences. Table below lists their similarities and differences.
Once an array is created, its size is fixed. You can access an array element using the square-bracket notation (e.g., a[index]). When an ArrayList is created, its size is 0.
You cannot use the get(index) and set(index, element) methods if the element is not in the list. It is easy to add, insert, and remove elements in a list, but it is rather complex to add, insert, and remove elements in an array. You have to write code to manipulate the array in order to perform these operations. Note that you can sort an array using the java.util.Arrays.sort(array) method. To sort an array list, use the java.util.Collections.sort(arraylist) method.
Suppose you want to create an ArrayList for storing integers. Can you use the following code to create a list?
ArrayList<int> list = new ArrayList<>();
No. This will not work because the elements stored in an ArrayList must be of an object type. You cannot use a primitive data type such as int to replace a generic type. However, you can create an ArrayList for storing Integer objects as follows:
ArrayList<Integer> list = new ArrayList<>();
The program below gives a program that prompts the user to enter a sequence of numbers and displays the distinct numbers in the sequence. Assume that the input ends with 0 and 0 is not counted as a number in the sequence.
The program creates an ArrayList for Integer objects (line 8) and repeatedly reads a value in the loop (lines 14–19). For each value, if it is not in the list (line 17), add it to the list (line 18). You can rewrite this program using an array to store the elements rather than using an ArrayList. However, it is simpler to implement this program using an ArrayList for two reasons.
- First, the size of an ArrayList is flexible so you don’t have to specify its size in advance. When creating an array, its size must be specified.
- Second, ArrayList contains many useful methods. For example, you can test whether an element is in the list using the contains method. If you use an array, you have to write additional code to implement this method.
You can traverse the elements in an array using a foreach loop. The elements in an array list can also be traversed using a foreach loop using the following syntax:
for (elementType element: arrayList) {
// Process the element
}
For example, you can replace the code in lines 22-23 using the following code:
for (int number: list)
System.out.print(number + “ “);
Top comments (0)