Reputation: 275
Consider flowing situation:
class A {
}
class B extends A {
}
List <? extends A> x = new ArrayList<A>();
List <? extends A> xx = new ArrayList<B>();
both 'x' and 'xx' are legal declarations in Java 6 and Java 7 (I know that in Java 7 you can also substitute the parameterized type of the constructor with an empty set of type parameters (<>). However, I wonder, what is the difference between 'x' and 'xx' in Java 6?
Upvotes: 5
Views: 316
Reputation: 20782
no difference. it all boils down to two lists of objects. You are just trying to coax the compiler to lend you a helping hand, as it's quite clever and could help you catch bad usage. You tell it that as long as the type in the List is-a A, all is fine. The compiler can then help highlighting any problems.
Upvotes: 1
Reputation: 887415
The way you wrote it, there is no difference.
At compile-time, both have the same type; namely, a List<>
of some unknown type that extends A
.
This is why you can't add anything to either list – you have no idea whether it's actually a List<B>
or a List<C>
or of some other type.
At runtime, they also have the same type; namely, List
. Due to type erasure, the type parameter doesn't exist at runtime.
Because you don't save any more strongly-typed references to it, no-one can tell that one of the lists is actually a List<B>
.
The point of these wildcards is for functions.
You can make a function that takes a List<? extends A>
, then pass it a List<B>
or a List<C>
, and the calling code can keep using the original list with its original type.
Upvotes: 6