Java Reference
In-Depth Information
Collection<String> col = ... // This code does not compile
because of the “...”.
// Add elements to col.
for (String s: col)
System.out.println(s);
This sugar hides
col.iterator()
, a method call that returns an
Iterator
instance for iterating over
col
's elements. It also hides calls to
Iterator
's
hasNext()
and
next()
methodsonthisinstance.Youinterpretthissugartoreadas
follows:“foreach
String
objectin
col
,assignthisobjectto
s
atthestartoftheloop
iteration.”
Note
Theenhancedforstatementisalsousefulinanarrayscontext,inwhichithides
the array index variable. Consider the following example:
String[] verbs = { "run", "walk", "jump" };
for (String verb: verbs)
System.out.println(verb);
Thisexample,whichreadsas“foreach
String
objectinthe
verbs
array,assignthat
objectto
verb
atthestartoftheloopiteration,”isequivalenttothefollowingexample:
String[] verbs = { "run", "walk", "jump" };
for (int i = 0; i < verbs.length; i++)
System.out.println(verbs[i]);
Theenhancedforstatementislimitedinthatyoucannotusethisstatementwhereac-
cess to the iterator is required to remove an element from a collection. Also, it is not
usable whereyoumustreplace elements inacollection/arrayduringatraversal, andit
cannot be used where you must iterate over multiple collections or arrays in parallel.
Tip
Tohaveyourclassessupporttheenhancedforstatement,designtheseclassesto
implement the
java.lang.Iterable
interface.
Autoboxing and Unboxing
DeveloperswhobelievethatJavashouldsupportonlyreferencetypeshavecomplained
about Java's support for primitive types. One area where the dichotomy of Java's type
systemisclearlyseenistheCollectionsFramework:youcanstoreobjectsbutnotprim-
itive type-based values in collections.
Althoughyoucannotdirectlystoreaprimitive type-basedvalueinacollection, you
canindirectlystorethisvaluebyfirstwrappingitinanobjectcreatedfromaprimitive