Java 运行时已知的通用上界通配符实例化 类脂肪族扩展有机{} 己烷类扩展脂肪族{} 公共类有机食品{ 空位反应(E){} 静态void main(字符串[]参数){ 有机
非常简单,如果您有一个泛型类型的对象,该对象的类型参数Java 运行时已知的通用上界通配符实例化 类脂肪族扩展有机{} 己烷类扩展脂肪族{} 公共类有机食品{ 空位反应(E){} 静态void main(字符串[]参数){ 有机,java,generics,wildcard,bounded-wildcard,Java,Generics,Wildcard,Bounded Wildcard,非常简单,如果您有一个泛型类型的对象,该对象的类型参数T用扩展X通配符实例化,那么您就不能调用对象上的方法,这些方法采用T类型的参数,因为编译器不能保证类型安全。但是,您可以调用返回T的方法>(并将返回值指定给类型为X)的变量。在您的特定示例中,这看起来应该是安全的 public class WildcardCollection { public static void main (String[] args){ WildcardCollection w = new Wi
T
用扩展X
通配符实例化,那么您就不能调用对象上的方法,这些方法采用T
类型的参数,因为编译器不能保证类型安全。但是,您可以调用返回T
的方法>(并将返回值指定给类型为X
)的变量。在您的特定示例中,这看起来应该是安全的
public class WildcardCollection {
public static void main (String[] args){
WildcardCollection w = new WildcardCollection();
w.myMethod(new Items("hola",1)); //Compile
w.myMethod(new SubItems("nuevo",3)); //Compile
}
public <T extends Items> void myMethod(T a){ //Same as above
System.out.println("hi: "+a);
}
}
class SubItems extends Items {
SubItems(){};
SubItems(String s, int i){ super(s,i);}
}
class Items implements Comparable<Items> {
private String name;
private int value;
public Items() {}
public Items(String n, int i){ this.name = n; this.value = i;}
public String getName(){ return this.name;}
public int getValue(){ return this.value;}
public String toString(){ return "(" + this.name + "-" + this.value + ")";}
public int compareTo(Items i){
return this.value - i.getValue();
}
}
这显然是不正确的-这与
Organic<? extends Organic> compound = new Aliphatic<Hexane<?>>();
compound.react(new Organic());
Collectionrelated:和另一个插件-我从未发现关于泛型的问题无法通过引用该站点来回答。因此,如果您希望能够“添加”任何内容(即传入变量类型的参数),则允许声明引用是没有用的然后编译器需要能够计算出这些类型是兼容的,因此您需要一个具体的类型。Organic composite=new Aliphatic()
就可以了。为什么这个案例在WildcardCollection中工作?这个案例相同吗?不,您的WildcardCollection
示例不同,因为它不使用任何通配符或参数化类型。像myMethod
这样的泛型方法与泛型类型不同。
Organic<? extends Organic> compound = new Aliphatic<Organic>();
compound.react(new Organic());
Organic<? extends Organic> compound = new Aliphatic<Hexane<?>>();
compound.react(new Organic());
Collection<? extends Number> nums = new ArrayList<Float>();
nums.add(Integer.valueOf(1));