wood burning stoves 2.0*
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
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Generic, iteratorable ListModels and foreach loops