Pass
Pass

Reputation: 1501

Java Iterable<Iterable<T>> to ArrayList<ArrayList<T>>

Maybe I am missing something but I thought that If I declare my class as such:

public class Something<T> implements Iterable<Iterable<T>> {
  public Something(Iterable<Iterable<T>> input) {
  ...

I should be able to instantiate it as such:

ArrayList<ArrayList<String>> l = new ArrayList<ArrayList<String>>();

Something<String> s = Something<String>(l);

Unfortunately this gimes me an error. I thought ArrayLists are Iterable so that should map exactly to my constructor definition.

Upvotes: 2

Views: 4035

Answers (2)

mblinn
mblinn

Reputation: 3274

Subtyping with generics is very non-intuitive. For what you want to do, you need wildcards, and it would be pretty ugly.

There's a great explanation here in Section 3 - http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Upvotes: 1

Jeremy
Jeremy

Reputation: 22415

You need to modify your constructor to accept anything that extends Iterable<T>

public Something(Iterable<? extends Iterable<T>> list){}

The reason for this is because generic types cannot literally extend other generic types. A List<String> cannot be assigned to a List<CharSequence>. The keyword extends allows this type of assignment to occur.

Upvotes: 7

Related Questions