为了理解 java 中的泛型,我编写了以下代码。
问题是 - 我应该如何参数化myBox
以便它接受FilterType <?> myFilterType
?
public class Generics {
/**
* @param args
*/
public static void main(String[] args) {
Generics g = new Generics();
Object myValue = "putThisIntoTheBox";
FilterType<?> myFilterType3 = g.new FilterType<>(null); //works
Box myBox3 = g.create(myFilterType3, myValue); //fails - create won't accept myFilterType3
}
public <T> Box<T> create(FilterType<T> type, T value) {
return new Box<T>(value);
}
//CLASSES
public class FilterType<T>{
T type;
public FilterType(T type) {
this.type = type;
}
}
public class Box<T>{
T value;
public Box(T value) {
this.value = value;
}
}
}