Java Reference
In-Depth Information
12. list.add(“OH”);
13. list.add(“CO”);
14. list.add(“NE”);
15. list.add(“NJ”);
16. String state = list.get(2);
17. System.out.println(state);
18. if(list.contains(“CO”)) {
19. System.out.println(list.indexOf(“CO”));
20. }
21. Iterator<String> iter = list.iterator();
22. while(iter.hasNext()) {
23. System.out.println(iter.next());
24. }
25. list.clear();
26. System.out.println(list.size());
The sequence of events for the previous statements is as follows:
1.
Lines 12-15 add four strings to
list
.
2.
Line 16 sets
state
to the element at index
2
, which is the third element,
“NE“
. Because
of generics, there is no need to cast the return value of
get
to a
String
.
3.
Line 18 is
true
and line 19 displays the index of
“CO“
, which is
1
.
4.
Line 21 returns an
Iterator
for
list
, a common technique for iterating through a list.
Using generics, the
Iterator
declares its elements as
String
types, which is consistent
with the data types in
list
.
5.
The
while
loop on lines 22-24 demonstrates the
hasNext
and
next
methods of
Iterator
, displaying each
String
in
list
on a separate line.
6.
Line 25 removes all elements from the list, so printing the size on line 26 outputs
0
.
The output of the code is
NE
1
OH
CO
NE
NJ
0
Search WWH ::
Custom Search