Iterator iter = employees.iterator();
Employee emp = (Employee) iter.next();
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.
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
The ClassCastException occursbecauseofanassumptionthatalistis homo-
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