Two Laptop Bag*
The moose likes Java in General and the fly likes Generic, iteratorable ListModels and foreach loops Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generic, iteratorable ListModels and foreach loops" Watch "Generic, iteratorable ListModels and foreach loops" New topic
Author

Generic, iteratorable ListModels and foreach loops

Stevo Johnson
Greenhorn

Joined: Jun 01, 2009
Posts: 12
Hey everyone!

I am writing my own ListModel that supports generics and provides an API to ArrayLists. I decided to implement the Iterable interface so I could use foreach loops on my ListModels but I'm running into trouble.

My iterator implementation in MyListModel looks like this:




In my test code I am able to write this fine:



But when I switch to a foreach loop I get errors:



Namely this one: "Error: Type mismatch: cannot convert from element type Object to Integer"


What I've been reading about the foreach loop suggests that if the top one works the bottom one should to. Anyone know what I am doing wrong here?
Stevo Johnson
Greenhorn

Joined: Jun 01, 2009
Posts: 12
Solved my problem!

When declaring the class you must specify the generic behind the "implements Iterable"

i.e.



Originally I forgot the <E> after Iterable in the class declaration.
 
jQuery in Action, 2nd edition
 
subject: Generic, iteratorable ListModels and foreach loops
 
Similar Threads
Question about cycling through hasmap keys
what is difference between foreach and for?
Regarding generics, mixed with legacy collection code.
Iterator in Generics
My sad little program can't seem to count cards right