I have seen in multiple different places people who instantiate a list or ArrayList like:
List<?> l = new ArrayList<>();
What type is ?? Does this mean that it can hold any types in it? If so, why would this be used instead of just and ArrayList?
In Java, List is an interface. That is, it cannot be instantiated directly.
Does this mean that it can hold any types in it?
No. It means that your l
variable could be referring to a list parameterized with any type. So it's actually a restriction: you will not be allowed to add any object to l
because you have no idea which items it accepts. To give a concrete example, l
could be a List<String>
or it could be a List<ExecutorService>
.
As correctly pointed by Marko, its an unknown restriction on the List type.
The Java docs says that:
The unbounded wildcard type is specified using the wildcard character (?), for example,
List<?>
. This is called a list of unknown type. There are two scenarios where an unbounded wildcard is a useful approach:
- If you are writing a method that can be implemented using functionality provided in the Object class.
- When the code is using methods in the generic class that don't depend on the type parameter. For example, List.size or List.clear. In fact,
Class<?>
is so often used because most of the methods in Class do not depend on T.
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