Java – use wildcards to create new generic objects
Please explain the compilation time error of this generic code wildcard:
//no compile time error. List<? extends Number> x = new ArrayList<>(); //compile time error. List<? extends Number> x = new ArrayList<? extends Number>();
Solution
Instantiating a generic type using wildcards is invalid syntax List type extension number > indicates that a list of a certain type is or extension number It is meaningless to create instances of this type, because you create something specific by instantiation:
new ArrayList<? extends Number>();//compiler:"Wait,what am I creating exactly?"
Generic types with wildcards only make sense for variables and method parameters because they are more freely assigned / passed to them
//compiler:"Okay,so passing in a List<Integer> or a List<Double> are both fine" public void eatSomeNumbers(List<? extends Number> numbers) { for (Number number : numbers) { System.out.println("om nom " + number + " nom"); } }
Be sure to remember the limitations of using wildcards
List<? extends Number> numList = ... numList.add(new Integer(3));//compiler:"Nope,cause that might be a List<Double>"
For your first example, the diamond is a new feature in Java 7 that allows the compiler to infer the type of a new generic instance based on the type of variable assigned to it under these circumstances:
List<? extends Number> x = new ArrayList<>();
The compiler is likely to infer the new ArrayList < number > () here, but the inference is almost unimportant as long as it is a valid assignment to a given variable That's why the diamond operator was introduced – specifying a generic type for a new object is redundant, as long as some generic types will make it a valid assignment / parameter
This reasoning makes sense if you remember that generics in Java are pure compile time language functions because of type erasure and have no meaning at run time Wildcards exist only because of this restriction In contrast, in c# generic types, the information is near runtime - Generic wildcards do not exist in the language