Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type is <?> when making instantiating lists?

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?

like image 685
DITTO Avatar asked Aug 29 '15 19:08

DITTO


People also ask

Can you instantiate a list?

In Java, List is an interface. That is, it cannot be instantiated directly.


2 Answers

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>.

like image 78
Marko Topolnik Avatar answered Nov 02 '22 14:11

Marko Topolnik


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.
like image 44
Rahul Tripathi Avatar answered Nov 02 '22 14:11

Rahul Tripathi