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?
In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).
The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.
We can use the Java Wildcard as a local variable, parameter, field or as a return type. But, when the generic class is instantiated or when a generic method is called, we can't use wildcards. The wildcard is useful to remove the incompatibility between different instantiations of a generic type.
Do not use wildcard types as return types.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With