aspose file tools*
The moose likes Beginning Java and the fly likes Handling methods for an object that is held in an ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Handling methods for an object that is held in an ArrayList" Watch "Handling methods for an object that is held in an ArrayList" New topic
Author

Handling methods for an object that is held in an ArrayList

Adam Cripps
Ranch Hand

Joined: Oct 01, 2011
Posts: 41

I have a set of classes (CurriculumSubject) that has a method (getItems).



I create these objects and add them to an array list (this is a short example).



Later on, I want to access this list and then get the items from each item in the list.



The getName reference works and I can see output in the console which shows the correct list.
However, when I try the cast to get a hold of the getItems method in CurriculumSubject, I get the error:



How do I make sure my classes play nicely so that I can cast the ArrayList object item to my CurriculumSubject class? I read in a google search that if I don't do the cast, then my ArrayList item objects are very similar to Object class and don't have any of my methods.

Any advice gratefully received.
TIA
Adam
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6



The error message is telling you exactly what's wrong. Namely, An Iterator is not a CurriculumSubject, and hence cannot be treated like one. An Iterator's next() method, however, can return a CurriculumSubject.

Note that "l" is a horrible variable name.

Also note that you could do away with the cast ant the explicit iterator by using Generics and the Foreach loop:



Adam Cripps
Ranch Hand

Joined: Oct 01, 2011
Posts: 41

Thanks for the pointer - I wasn't clear on what the iterator was doing, but it makes more sense now.

However, all it's done is throw up another problem in my code - but I'll research that one and save it for another thread (if I need it).

Thanks again.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Handling methods for an object that is held in an ArrayList