Java generics and iterators
February 23, 2007The 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!