Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Since String is a final class, how can a wildcard <? extends String> be correct? [duplicate]

Tags:

java

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);
            }
like image 448
likejudo Avatar asked Sep 03 '25 03:09

likejudo


1 Answers

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.

like image 136
Silvio Mayolo Avatar answered Sep 04 '25 23:09

Silvio Mayolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!