The Java API provides several predefined data structures, called collections, used to store groups of related objects. These classes provide efficient methods that organize, store and retrieve your data without requiring knowledge of how the data is being stored. This reduces application-development time.
You’ve used arrays to store sequences of objects. Arrays do not automatically change their size at execution time to accommodate additional elements. The collection class ArrayList<T> (from package java.util
) provides a convenient solution to this problem—it can dynamically change its size to accommodate more elements. The T
(by convention) is a placeholder—when declaring a new ArrayList
, replace it with the type of elements that you want the ArrayList
to hold. This is similar to specifying the type when declaring an array, except that only nonprimitive types can be used with these collection classes. For example,
ArrayList< String > list;
declares list
as an ArrayList
collection that can store only String
s. Classes with this kind of placeholder that can be used with any type are called generic classes. Additional generic collection classes and generics are discussed in Appendix J. Figure E.20 shows some common methods of class ArrayList<T>
.
Figure E.21 demonstrates some common ArrayList
capabilities. Line 10 creates a new empty ArrayList
of String
s with a default initial capacity of 10 elements. The capacity indicates how many items the ArrayList
can hold without growing. ArrayList
is implemented using an array behind the scenes. When the ArrayList
grows, it must create a larger internal array and copy each element to the new array. This is a time-consuming operation. It would be inefficient for the ArrayList
to grow each time an element is added. Instead, it grows only when an element is added and the number of elements is equal to the capacity—i.e., there’s no space for the new element.
1 // Fig. E.21: ArrayListCollection.java
2 // Generic ArrayList<T> collection demonstration.
3 import java.util.ArrayList;
4
5 public class ArrayListCollection
6 {
7 public static void main( String[] args )
8 {
9 // create a new ArrayList of Strings with an initial capacity of 10
10 ArrayList< String > items = new ArrayList< String >();
11
12 items.add( "red" ); // append an item to the list
13 items.add( 0, "yellow" ); // insert the value at index 0
14
15 // header
16 System.out.print(
17 "Display list contents with counter-controlled loop:" );
18
19 // display the colors in the list
20 for ( int i = 0; i < items.size(); i++ )
21 System.out.printf( " %s", items.get( i ) );
22
23 // display colors using foreach in the display method
24 display( items,
25 "
Display list contents with enhanced for statement:" );
26
27 items.add( "green" ); // add "green" to the end of the list
28 items.add( "yellow" ); // add "yellow" to the end of the list
29 display( items, "List with two new elements:" );
30
31 items.remove( "yellow" ); // remove the first "yellow"
32 display( items, "Remove first instance of yellow:" );
33
34 items.remove( 1 ); // remove item at index 1
35 display( items, "Remove second list element (green):" );
36
37 // check if a value is in the List
38 System.out.printf( ""red" is %sin the list
",
39 items.contains( "red" ) ? "": "not " );
40
41 // display number of elements in the List
42 System.out.printf( "Size: %s
", items.size() );
43 } // end main
44
45 // display the ArrayList's elements on the console
46 public static void display( ArrayList< String > items, String header )
47 {
48 System.out.print( header ); // display header
49
50 // display each element in items
51 for ( String item : items )
52 System.out.printf( " %s", item );
53
54 System.out.println(); // display end of line
55 } // end method display
56 } // end class ArrayListCollection
Display list contents with counter-controlled loop: yellow red
Display list contents with enhanced for statement: yellow red
List with two new elements: yellow red green yellow
Remove first instance of yellow: red green yellow
Remove second list element (green): red yellow
"red" is in the list
Size: 2
The add method adds elements to the ArrayList
(lines 12–13). The add
method with one argument appends its argument to the end of the ArrayList
. The add
method with two arguments inserts a new element at the specified position. The first argument is an index. As with arrays, collection indices start at zero. The second argument is the value to insert at that index. The indices of all subsequent elements are incremented by one. Inserting an element is usually slower than adding an element to the end of the ArrayList
Lines 20–21 display the items in the ArrayList
. The size method returns the number of elements currently in the ArrayList
. ArrayList
s method get (line 21) obtains the element at a specified index. Lines 24–25 display the elements again by invoking method display (defined at lines 46–55). Lines 27–28 add two more elements to the ArrayList
, then line 29 displays the elements again to confirm that the two elements were added to the end of the collection.
The remove method is used to remove an element with a specific value (line 31). It removes only the first such element. If no such element is in the ArrayList
, remove
does nothing. An overloaded version of the method removes the element at the specified index (line 34). When an element is removed, the indices of all elements after the removed element decrease by one.
Line 39 uses the contains method to check if an item is in the ArrayList
. The contains
method returns true
if the element is found in the ArrayList
, and false
otherwise. The method compares its argument to each element of the ArrayList
in order, so using contains
on a large ArrayList
can be inefficient. Line 42 displays the ArrayList
’s size.