Java Reference
In-Depth Information
Collection<String> col = ... // This code does not compile
because of the “...”.
// Add elements to col.
for (String s: col)
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
Note Theenhancedforstatementisalsousefulinanarrayscontext,inwhichithides
the array index variable. Consider the following example:
String[] verbs = { "run", "walk", "jump" };
for (String verb: verbs)
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++)
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
about Java's support for primitive types. One area where the dichotomy of Java's type
itive type-based values in collections.
Althoughyoucannotdirectlystoreaprimitive type-basedvalueinacollection, you
Search WWH ::

Custom Search