Java Reference
In-Depth Information
employees.add("Jack Frost");
Iterator iter = employees.iterator();
while (iter.hasNext())
{
Employee emp = (Employee) iter.next();
System.out.println(emp.getName());
}
}
}
thenusesthislistcollectionobject'sreferencetoaddapairof
Employee
objectstothe
list.Itthenaddsa
String
object,whichviolatestheimpliedcontractthat
ArrayList
is supposed to store only
Employee
objects.
Movingon,
main()
obtainsa
java.util.Iterator
instanceforiteratingover
thelistof
Employee
s.Aslongas
Iterator
's
hasNext()
methodreturnstrue,its
next()
method is called to return an object stored in the array list.
The
Object
that
next()
returnsmustbedowncastto
Employee
sothatthe
Em-
ployee
object's
getName()
method can be called to return the employee's name.
Thestringthatthismethodreturnsisthenoutputtothestandardoutputdevicevia
Sys-
tem.out.println()
.
The
(Employee)
castchecksthetypeofeachobjectreturnedby
next()
tomake
sure that it is
Employee
. Although this is true of the first two objects, it is not true
of the third object. Attempting to cast
"Jack Frost"
to
Employee
results in a
ClassCastException
.
The
ClassCastException
occursbecauseofanassumptionthatalistis
homo-
genous
.Inotherwords,aliststoresonlyobjectsofasingletypeorafamilyofrelated
types. In reality, the list is
heterogeneous
in that it can store any
Object
.
Listing 3-51.
Lack of type safety leading to a compiler error
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;