|
|
#1 | |
|
Mahna Mahna
Join Date: Jul 2006
Location: Madison, Wi
Posts: 6,123
|
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??
__________________
|
|
|
|
|
|
|
#2 | |
|
Registered User
Join Date: Jul 2005
Posts: 434
|
Quote:
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). |
|
|
|
|
|
|
#3 |
|
*BANNED*
Join Date: Sep 2006
Posts: 427
|
Why are you using < 1.5? You should really consider upgrading to at least 1.5, which added many useful constructs to the language.
|
|
|
|
|
|
#4 | |
|
Mahna Mahna
Join Date: Jul 2006
Location: Madison, Wi
Posts: 6,123
|
Quote:
Thanks for the help!!
__________________
|
|
|
|
|
|
|
#5 |
|
Registered User
Join Date: Jul 2005
Posts: 434
|
'tis true, and if you do end up working with Java in the real world, you never know when you might be called upon to update or maintain older code, as the majority of java code out there is going to be using older language constructs.... so you at least need to be able to understand how to read it. I'm forced to use 1.4 for some stuff due to products that don't officially support 1.5... and believe it or not, trying to run them with a 1.5 virtual machine does seem to cause issues.
|
|
|
|
![]() |
| Thread Tools | |
|
|