If you wanted to store an array of objects of type MyInterface, are the following both acceptable and if so when would you use the second form over the first?
i) Using only an interface:-
List<MyInterface> mylist = new ArrayList<MyInterface>();
ii) Using a generic wildcard:-
List<? extends MyInterface> mylist = new ArrayList<? extends MyInterface>();
Edit:
As the answers so far have pointed out, number ii won’t compile. What is the difference between i and a case iii where :-
iii) Using a generic wildcard only in the reference:-
List<? extends MyInterface> mylist = new ArrayList<MyInterface>();
Second one won’t compile. Imagine:
Then the following would match your second expression, but won’t compile:
Correction: Wrong one too:
It is right in a sense it does compile, but you cannot add any subclasses of MyInterface to it. Confusing, but correct — after I read the explanation. Same reason: wildcard can be viewed for example as:
So this won’t work:
and vice versa. Compiler refuses to do those potentially incorrect operations.
The option which allows you to add any subclass of MyInterface to mylist is: