Java泛型类与方法详解
1. 类型擦除与类型参数的上界
在Java中,当编译器将方法 maximum 转换为字节码时,会使用类型擦除(erasure)把类型参数替换为实际类型。例如,在某些情况下,所有泛型类型会被替换为 Object 类型。实际上,所有类型参数都会被替换为类型参数的上界,这个上界在类型参数部分指定。
以下是 maximum 方法经过类型擦除后的代码示例:
public static Comparable maximum(Comparable x, Comparable y, Comparable z)
{
Comparable max = x; // assume x is initially the largest
if (y.compareTo(max) > 0)
max = y; // y is the largest so far
if (z.compareTo(max) > 0)
max = z; // z is the largest
return max; // returns the largest object
}
类型擦除后, maximum 方法声明返回 Comparable 类型。但调用该方法的代码期望接收与传入参数相同类型的对象,如 Integer 、 Double
超级会员免费看
订阅专栏 解锁全文
10万+

被折叠的 条评论
为什么被折叠?



