Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add value to the Java collection with wildcard generic type

Tags:

java

generics

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) 
like image 714
Sergey Mikhanov Avatar asked Sep 15 '10 10:09

Sergey Mikhanov


People also ask

What is wildcard in Java generic?

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).

Where can you use a wildcard to denote a parameter type in your code?

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.

How do you add to a generic List in Java?

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);

Why do we use wildcards in Java generics?

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.


1 Answers

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.

like image 193
Jon Skeet Avatar answered Sep 22 '22 18:09

Jon Skeet