Java Reference
In-Depth Information
but this is a very different failure than what one would get in a language where a cast is an
assertion; in those languages, the program will merrily continue, but the result of the cast will
be garbage. In those languages, the result of such a cast will generally not appear until your
program has run merrily along for some time, and will cause it to crash far away from the ori-
ginal source of the problem—if you are lucky, that is. If you are not (and none of us are in the
long run; that's why we're programmers), then the result of such a cast will be data corruption
that won't be caught until some completely different program fails in an utterly inexplicable
way.
So, if we wanted to be really paranoid and careful about ensuring that we never caused the
program to fail because something that didn't support the Player interface crept into our Set
of Player objects in a Team , we could have written our FormatRoster() method like this:
public static void FormatRoster(Team toFormat){
Player p;
Object o;
System.out.println(toFormat.getName());
Iterator e = toFormat.getRoster().iterator();
while (e.hasNext()){
o = e.next();
if (o instanceof Player){
try{
p = (Player)o;
System.out.println("\t" + p.getName());
} catch (ClassCastException ex){
e.remove();
}
} else {
e.remove();
}
}
}
On this approach, we extract an Object from the Set using our Iterator , knowing that the
contents must be at least that. We then check to see whether the object that we got is an in-
stanceof the Player type; if it is not ,we will simply remove it from the list. Only then do
we cast, but being fully paranoid, we wrap our cast in a try block, so that if it fails, we will
catch the ClassCastException and, once again, remove the offending object from the list.
With both the belt and the suspenders, we can be sure that we will catch any offending object
that has been misplaced into our collection of Player objects.
Search WWH ::




Custom Search