Java generics and iterators

The java type system, with the introduction of generics, presents a number of quirks. The following is a situation I’ve recently come across.
Suppose you have an interface IAnimal and a class Cow implementing it. Consider the following java code:

// IFarm.java
interface IFarm extends Iterable {
// ...
}

// CowFarm.java
class CowFarm implements IFarm {
private ArrayList<Cow> cows = new ArrayList<Cow>();
public Iterator<IAnimal> iterator() {
// what goes here?!?
}
}

How would you implement the iterator method?
A simple

return cows.iterator();

won’t work, because the java compiler does not consider Iterator<Cow> a subtype of Iterator<IAnimal>.

It turns out that the best way to address the problem is to resort to type erasure and suppress the resulting warning!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: