Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Handling methods for an object that is held in an ArrayList

 
Adam Cripps
Ranch Hand
Posts: 41
Eclipse IDE Linux Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • 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 Linux Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic