• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Handling methods for an object that is held in an ArrayList

 
Ranch Hand
Posts: 41
Eclipse IDE Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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
Posts: 41
Eclipse IDE Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic