Java泛型。为什么要编译?

Groxel:
abstract class Type<K extends Number> {
    abstract <K> void use1(Type<K> k);           // Compiler error (Type parameter K is not within its bounds)
    abstract <K> void use2(Type<? extends K> k); // fine
    abstract <K> void use3(Type<? super K> k);   // fine
}

该方法一般K型阴影类通用型K,所以<K>不匹配<K extends Number>use1().The编译器不知道的新的通用型的任何有用<K>use2()use3(),但它仍然是合法的编译。为什么<? extends K>(或<? super K>)的比赛<K extends Number>

axtavt:

首先,让我们重写它以避免阴影:

abstract class Type<N extends Number> {
    abstract <K> void use1(Type<K> k); 
    abstract <K> void use2(Type<? extends K> k); 
    abstract <K> void use3(Type<? super K> k);   
}

在第一种方法KType<N extends Number>,它充当的类型参数,因此其值应符合Type的范围N但是,方法声明对的值没有任何限制K,因此不合法。如果您对以下内容添加必要的限制,那将是合法的K

abstract <K extends Number> void use1(Type<K> k);

在以下方法中,的实际类型参数Type为unknown(?),并对其K附加了一定的绑定,因此这些声明中没有任何非法的地方。

这是带有类似声明的更实际的示例:

class MyList<N extends Number> extends ArrayList<N> {}

<K> void add1(MyList<K> a, K b) {
     a.add(b); // Given the method declaration, this line is legal, but it 
          // violates type safety, since object of an arbitrary type K can be
          // added to a list that expects Numbers
          // Thus, declaration of this method is illegal
}

<K> void add2(MyList<? extends K> a, K b) {
     // a.add(b) would be illegal inside this method, so that there is no way
     // to violate type safety here, therefore declaration of this method is legal
}

<K> void add3(MyLisy<? super K> a, K b) {
     a.add(b); // This line is legal, but it cannot violate type safey, since
          // you cannot pass a list that doesn't expect K into this method
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章