Java Reference
In-Depth Information
public void listDogs() {
Collection c = getBreed("labrador");
for (Iterator i = c.iterator(); i.hasNext(); )
String name = ((Dog) i.next()).getName();
System.out.println(name);
}
}
This does work; however, although we know that the returned
List
must contain a list
of
Dogs
, there is nothing to stop someone else from compiling source code that assumes
that the list contains
Cats
—it will compile without problems. However, if that happens, a
ClassCast-Exception
will be thrown at runtime.
To get around that, you would have to write explicit type checking into your code (using
the
instanceof
operator) and/or catch
ClassCastException
.
It is much nicer when we can ensure that a generic class will be handled correctly at run-
time. Consider the following replacement for the
getBreed
and
listDogs
methods:
public List<Dog> getBreed(String breedName) {
List<Dog> dogs = new ArrayList<Dog>();
// do some work to find the correct dogs
String dogName = "Labrador";
Dog pooch = new Dog(dogName);
dogs.add(pooch);
return dogs;
}
public void listDogs() {
Collection<Dog> c = getBreed("labrador");
for (Iterator<Dog> i = c.iterator(); i.hasNext(); ) {
String name = i.next().getName();
System.out.println(name);
}
}
We have now specified that the return type of the
getBreed
method will be a
List
of
Dogs
.
(It may help to read
List<Dog>
as
List
of
Dog
).
Note that the line
String name = i.next().getName();
does not cast the class anymore—
the line defining the
Iterator
specifies its type.
Attempting to cast an item in the collection to a nonrelated class produces the following
error:
GenericExample.java:16: inconvertible types
found : Dog
required: Cat
String name = ((Cat) i.next()).getName();
^
1 error