Java Reference
In-Depth Information
1
// Fig. 7.24: 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 "yellow" 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 enhanced for in the display method
24
display(items,
25
"%nDisplay 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%n" ,
39
items.contains( "red" ) ? "" : "not " );
40
41
// display number of elements in the List
42
System.out.printf( "Size: %s%n" , items.size());
43
}
44
45
// display the ArrayList's elements on the console
46
public static void display(ArrayList<String> items, String header)
47
{
48
System.out.printf(header); // display header
49
50
// display each element in items
51
for (String item : items)
52
System.out.printf( " %s" , item);
53
Fig. 7.24 | Generic ArrayList<T> collection demonstration. (Part 1 of 2.)
Search WWH ::




Custom Search