Thread: Casting Help
View Single Post
Old 10-29-07, 09:25 PM   #2
rhink
Registered User
 
Join Date: Jul 2005
Posts: 434
Default Re: Casting Help

Quote:
Originally Posted by jcrox
Java:

I have an Interface called Analyzer and 3 classes that implement the interface. In the processing class I want to loop an Arraylist of the objects and call the methods they implement from the Interface... I know I can do this with the newest version of java:

private Arraylist<Analyzer> list = new Arraylist<Analyzer>;

SummaryReport summary = new SummaryReport();
UniqueToken token = new UniqueToken();
TokenCount count = new TokenCount();

list.add(summary);
list.add(token);
list.add(count);

for (Analyzer item : list) {
processToken();
}

but how do I do that same thing for older versions of java?? help anyone??
you can't use generics for 1.4 and earlier, so for creating your arraylist:

private Arraylist list = new Arraylist();

You also can't use the funky new for loop parameters... easiest thing is probably an iterator/while loop:

Iterator iterator = item.iterator();
while(iterator.hasNext()) {
Analyzer temp = (Analyzer)iterator.next(); //this explicitly casts the "Object" coming out of your ArrayList into an "Analyzer"

//do stuff with your analyzer here....
}

Generics (the ArrayList<Analyzer> kind of notation) does basically the same thing. The only difference is, it'll catch logic errors at compile time that would otherwise be caught at run time.... in other words, the compiler will find an error if you tried to stick an object other than an "Analyzer" into the arraylist if you're using generics.... if you tried that with normal casting, the compiler will be perfectly happy, but when you try the explicit cast yourself (the Analyzer temp = (Analyzer)iterator.next() thing), you'll get an "Invalid class cast exception" if the object in your list is anything but an Analyzer.... (or compatible derived class).
rhink is offline   Reply With Quote