One might expect the parameter to have the type List. That way, it seems likely, you could call it with parameters of type List or List for any class E. Explain carefully what is wrong with this argument and why the type List is used instead.
时间: 2024-03-01 07:54:56 浏览: 83
The argument that the parameter should have the type `List<E>` instead of `List<? extends E>` is based on the assumption that `List<E>` can be used to represent a list of any type of object. However, this assumption is incorrect. Consider the following example:
```
List<String> strings = new ArrayList<>();
List<Object> objects = strings; // Not allowed
objects.add(1);
String s = strings.get(0); // Throws ClassCastException at runtime
```
Here, `strings` is a `List<String>` and `objects` is a `List<Object>`. If we were allowed to assign `strings` to `objects`, we could add an integer to `objects`, violating the type safety of `strings`. This is why Java does not allow such an assignment.
Now, consider a method with a parameter of type `List<E>`. The following call might seem valid:
```
List<Object> objects = new ArrayList<>();
foo(objects);
```
However, if `foo` adds an element of type `E` to the list, it would violate the type safety of `objects`. This is why Java uses a bounded wildcard `List<? extends E>` instead of `List<E>`. This ensures that the method cannot add elements to the list, only read them, and does not violate the type safety of the argument list.
阅读全文