Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collections Wildcard

Tags:

java

generics

I am trying to define a List object and then add objects to it using the code below:

List<? extends File> newFiles = new ArrayList<? extends File>();

When I try to define it like that, I get a compiler error

Cannot instantiate the type ArrayList<? extends File>

whereas

List<? extends File> newFiles = new ArrayList<File>()

seems to be valid. It is not clear why.

File is a bean object I created-not the object belonging to the Java API.

like image 671
user5053360 Avatar asked Nov 27 '25 10:11

user5053360


1 Answers

You're not capable of directly instantiating a wildcard type. In this case, that would be ? extends File.

What you can do is simply use File, as extends implies an upper-bound relationship (you're guaranteed that the elements in that collection are at least File)...

List<? extends File> newFiles = new ArrayList<File>();

...or you could use the diamond notation in Java 7+, which is more idiomatic nowadays.

List<? extends File> newFiles = new ArrayList<>();

After a bit of a rethink, are you sure you want that wildcard? With generics, if you're using bound types, the rule to remember is PECS - Producer Extends, Consumer Super. As a producer, that list cannot be added to any further, in spite of the fact that it's empty.

It may be better to do away with the generic type bound altogether for your use case.

like image 153
Makoto Avatar answered Nov 30 '25 01:11

Makoto



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!