What does List<?> mean in java generics?

Viewed 52090

What does List<?> mean, does it mean simply a list of objects of unspecified type?

Googling for the string <?> returns nothing useful (:

11 Answers
  • List: There is no type restriction and assignment restriction at all.
  • List<Object>: It seems to be used the same as List, but a compilation error will occur when accepting other generic assignments.
  • List<?>: It is a generic type. Before assignment, it means that it can accept any type of set assignment, but after assignment, you can't add elements to it, but you can remove and clear, not an immutable set. List<?> is generally used as a parameter to receive an external collection, or return a collection of specific element types, also known as a wildcard collection.

The test code and result as followed:

        List a1 = new ArrayList();
        a1.add(new Object());
        a1.add(new Integer(10));
        a1.add(new String("string"));

        System.out.println("List is : " + a1);

        List<?> a4 = a1;
        a4.remove(0);
        System.out.println("List is : " + a4);

        System.out.println("List is : " + a4.get(0));
        
        a4.clear();
        System.out.println("List is : " + a4);

The result is :

List is : [java.lang.Object@2a139a55, 10, string]
List is : [10, string]
List is : 10
List is : []

? is nothing but Wildcard in Generics

There are 3 different kind of Wildcards in Generics

1) Upper Bounded Wildcards: Uses extends key word

eg: List<? extends SuperClass>

2) Lower Bounded Wildcards

eg:Uses Super key word List<? super SubClass>

3) Unbounded Wildcard

List<?> list

List<?> is equivalent to List<? extends Object>

The wildcard ? extends Object is equivalent to the unbounded wildcard ?

<?> in java specification

Generics in java specification

Related