Why this code does not compile (Parent
is an interface)?
List<? extends Parent> list = ... Parent p = factory.get(); // returns concrete implementation list.set(0, p); // fails here: set(int, ? extends Parent) cannot be applied to (int, Parent)
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.
You can get and insert the elements of a generic List like this: List<String> list = new ArrayList<String>; String string1 = "a string"; list. add(string1); String string2 = list. get(0);
Wildcards in Java are basically the question marks which we use in generic programming, it basically represents the unknown type. We use Java Wildcard widely in situations such as in a type of parameter, local variable, or field and also as a return type.
It's doing that for the sake of safety. Imagine if it worked:
List<Child> childList = new ArrayList<Child>(); childList.add(new Child()); List<? extends Parent> parentList = childList; parentList.set(0, new Parent()); Child child = childList.get(0); // No! It's not a child! Type safety is broken...
The meaning of List<? extends Parent>
is "The is a list of some type which extends Parent
. We don't know which type - it could be a List<Parent>
, a List<Child>
, or a List<GrandChild>
." That makes it safe to fetch any items out of the List<T>
API and convert from T
to Parent
, but it's not safe to call in to the List<T>
API converting from Parent
to T
... because that conversion may be invalid.
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