Java - Generics Unbounded Wildcards

Introduction

Wrapper<Object> type and Wrapper<String> type are not assignment compatible.

For example, there is a compile-time error.

public class Main {
  public static void main(String[] args) {
    Wrapper<Object> objectWrapper = new Wrapper<Object>(new Object());
    printDetails(objectWrapper); // OK

    Wrapper<String> stringWrapper = new Wrapper<String>("Hello");
    printDetails(stringWrapper); // A compile-time error

  }
  public static void printDetails(Wrapper<Object> wrapper){
  }
}

class Wrapper<T> {
  public Wrapper(T ref) {}
}

Unbounded Wildcards

<?> for generic type is like Object to raw type.

A wildcard type is denoted by a question mark as <?>.

You can assign a generic of known type to a generic of wildcard type. Here is the sample code:

Wrapper of String type

Wrapper<String> stringWrapper = new Wrapper<String>("Hi");

You can assign a Wrapper<String> to Wrapper<?> type

Wrapper<?> wildCardWrapper = stringWrapper;

<?> denotes an unknown type.

wildCardWrapper has unknown type

Wrapper<?> wildCardWrapper;

The compile time error in the code above can be changed to

Demo

public class Main {
  public static void main(String[] args) {
    Wrapper<Object> objectWrapper = new Wrapper<Object>(new Object());
    printDetails(objectWrapper); // OK

    Wrapper<String> stringWrapper = new Wrapper<String>("Hello");
    printDetails(stringWrapper); // A compile-time error

  }//from ww w .ja v a2s.co m
  public static void printDetails(Wrapper<?> wrapper){ //Here is the fix
  }
}

class Wrapper<T> {
  public Wrapper(T ref) {}
}

Quiz