1

I have this pseudo code :

Example A
Interface Option
Class OptionImplementer implements Option
ArrayList<ArrayList<? extends Option>> test = new ArrayList<ArrayList<OptionImplementer>>(); <-- Fails?

Why does it fail? Child does implement Option, and I've also tried Super keyword instead of extends.

As "bonus" question, these constructor signatures are postulated to have same erasure:

 Example B
    public void test(ArrayList<ArrayList<? extends Option>> test) {

}
public void test(ArrayList<ArrayList<OptionImplementer>> test) {

}

Example A or B should work. A fails so be B should work...

  • 2
    It does not fail. Maybe you should post the exact code with the exact compiler error you are getting. – Marko Topolnik Oct 22 '12 at 11:43
  • It's not clear what the bonus question actually is. – Ricky Clarkson Oct 22 '12 at 12:23
  • Sorry, why does B example fail when A example also fails? *A* gives this error: 'Type mismatch: cannot convert from ArrayList> to ArrayList>' *B* gives 'Method test(ArrayList>) has the same erasure test(ArrayList) as another method in type Test' – Nino Martinez Wael Oct 22 '12 at 12:31

2 Answers2

2

Are you sure it fails? It shouldn't, and it doesn't when I try this:

interface Option {}
class Child implements Option {}

public class Example {
    public static void main(String[] args) {
        ArrayList<? extends Option> list = new ArrayList<Child>();
    }
}

Note, however, that you cannot add anything to list if you write it like this. Why you can't add to such a list has been asked many times before, see for example:

Community
  • 1
  • 1
Jesper
  • 186,095
  • 42
  • 296
  • 332
1

This is because a

ArrayList<ArrayList<? extends Option>>

can contain both entries of type ArrayList<Option> and ArrayList<OptionImplementer> although

ArrayList<ArrayList<OptionImplementer>>()

can only contain entries of the second type. In the first case, the following is allowed:

test.add(new ArrayList<Option>());
test.add(new ArrayList<OptionImplementer>());

Concerning your second question, it is unrelated but it just means that if you remove all generic info, the methods would have the same signature, which is not allowed.

Didier L
  • 13,411
  • 5
  • 46
  • 90
  • :( so theres no way to do something like this: 'ArrayList> test = new ArrayList>();' – Nino Martinez Wael Oct 23 '12 at 08:13
  • Not without tricking the compiler because this "cast" would allow you to corrupt your `ArrayList>` with `ArrayList – Didier L Oct 23 '12 at 11:59
  • Thanks, I figured it would be something like that :( – Nino Martinez Wael Oct 24 '12 at 09:00