Type Safety and Wildcard Generics: Understanding the Forbidden Modifier
When working with generic collections in Java, the concept of wildcard generics can introduce certain limitations that may initially seem counterintuitive. A prime example is the inability to add values to a Java collection with a wildcard generic type.
Consider the following code snippet:
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)
Why does this code fail to compile? The answer lies in the inherent safety mechanisms that are enforced bywildcard generics.
The Principle of Unrestricted Retrieval and Restricted Addition
The wildcard generic type, denoted by ? extends Parent, represents a list of elements that are descendants of the Parent interface. While it allows unrestricted retrieval of these elements, type safety dictates restrictions on adding values to the collection.
If the code were allowed to compile, it would permit the assignment of a Parent instance to an element within the list. However, this action could potentially break type safety.
Consider the following scenario:
List<Child> childList = new ArrayList<>(); 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...
In this scenario, a list of Child objects is cast to a list of ? extends Parent. The subsequent assignment of a Parent instance to the first element of the list violates type safety, as the resulting list contains an element that is not a valid Child instance.
Ensuring Immutable Type Safety
By prohibiting the addition of values to wildcard generic collections, Java enforces immutable type safety. This ensures that the list's elements always adhere to the constraints imposed by its declared type.
In the absence of this restriction, type safety would be compromised, leading to potential errors and unexpected behavior.
The above is the detailed content of Why Can't I Add Elements to a Java Collection with a Wildcard Generic Type (`? extends Parent`)?. For more information, please follow other related articles on the PHP Chinese website!