In a course on Spring Batch, I was surprised to see ? extends String
.
Since String is a final class, how is this correct?
public void write(List<? extends String> items) throws Exception {
System.out.println(String.format("Received list of size: %s", items.size()));
items.forEach(System.out::println);
}
You're correct that there will never be another class that extends String
. So the only type that can fill that ?
is String
itself. However, the extends
/ super
still conveys intent. Namely, a List<? extends String>
is a read-only list. You can't add elements to it since ? extends String
is a producer. A List<String>
is potentially a read-write collection. So by writing List<? extends String>
, we're conveying to whoever is reading the code (and to the compiler) that we only intend to read values from this List
, not write anything back.
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