2

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.

0

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but now I am getting warnings here: public class Something<T> implements Iterable<Iterable<T>> { private Iterable<Iterable<T>> input; public Something(Iterable<? extends Iterable<T>> input) { this.input = (Iterable<Iterable<T>>)input; }
I suggest find a copy of Effective Java by Josh Bloch and read up on "PECS". It will help you really understand what is going on. In any case, you need to have Iterable<? extends Iterable<T> everywhere you expect to assign ArrayList<ArrayList<String>>
or perhaps even Iterable<? extends Iterable<? extends T>>
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.