Consider the following piece of code:
class Test{
static <T> List<T> lstOf(T ...values){
List<T> lst = new ArrayList<T>(values.length);
for ( T val : values)
lst.add(val);
return lst;
}
static class Obj<T>{
T value;
public Obj(T val){
this.value = val;
}
}
public static void main(String [] args){
Obj<Integer> intVal = new Obj<Integer>(22);
Obj<Long> longVal = new Obj<Long>(22L);
List<Obj<? extends Number>> lst = lstOf(intVal, longVal);
}
}
The compiler complains that "lst" is of type
java.util.List<Test.Obj<? extends java.lang.Number&java.lang.Comparable<? extends java.lang.Number&java.lang.Com开发者_运维知识库parable<?>>>>
What is the type of the list object returned by lstOf method? How do I successfully assign a type to the returned value?
The inferred type is List<Test.Obj<? extends Number & Comparable<? extends Number & Comparable<?>>>>
as the message indicates. This is because Java is picking the most specific type that is common to the arguments it is given (both have type arguments that are Number
s that implement Comparable
). To make it just use the type you're interested in, Obj<? extends Number>
, call it as:
List<Obj<? extends Number>> lst = Test.<Obj<? extends Number>>lstOf(intVal, longVal);
ColinD has the detailed answer, but I would suggest instead specifying lst
:
List<? extends Obj<? extends Number>> lst = lstOf(intVal, longVal);
It is a type of the parameter you're passing to the method.
If you call lstOf(String ... strs)
then the result is List<String>
.
精彩评论