... ArrayList<String> items = new ArrayList<String>();
9
10         items.add("red"); // append an item to the list
11         items.add(0, "yellow"); // insert "yellow" at index 0
12
13         // header
14         System.out.print(
15            "Display list contents with counter-controlled loop:");
16
17         // display the colors in the list
18         for (int i = 0; i < items.size(); i++) {
19            System.out.printf(" %s", items.get(i));
20         }
21
22         // display colors using enhanced for in the display method
23         display(items,
24            "%nDisplay list contents with enhanced for statement:");
25
26         items.add("green"); // add "green" to the end of the list
27         items.add("yellow"); // add "yellow" to the end of the list
28         display(items, "List with two new elements:");
29
30         items.remove("yellow"); // remove the first "yellow"

Get Java How to Program, Early Objects, 11th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.