为什么这种通用方法不给出编译时错误



在此程序中,我正在创建一个通用方法,其中第二个参数扩展了第一个参数,但是当我将字符串作为第一个paameter和Integer数组作为第二个参数传递时,则程序也可以正常运行。为什么整数不扩展字符串,为什么不给编译时间错误?

class GenericMethodDemo {
    static <T, V extends T> boolean isIn(T x, V[] y) {
        for (int i = 0; i < y.length; i++) {
            if (x.equals(y[i])) {
                return true;
            }
        }
        return false;
    }
    public static void main(String args[]) {
        Integer nums[] = {1, 2, 3, 4, 5};
        if (!isIn("2", nums)) {
            System.out.println("2 is not in nums");
        }
    }
}

此编译而没有错误,因为类型系统将推断两个类型参数之间最近的常见超构型。

在提供的示例中,最近的常见超级类型是Object

如果我们提供双重,因为第一个参数Number将是推断类型,因为它是DoubleInteger之间最近的常见超级型。

public static void main(String args[]) {
    Integer nums[] = {1, 2, 3, 4, 5};
    //In this case the nearest common type is object
    if (!isIn("2", nums)) {
        System.out.println("2 is not in nums");
    }
    //In this case the nearest common type would be Number
    if (!isIn(2d, nums)) {
        System.out.println("2 is not in nums");
    }        
}

正如AzureFrog所说的,要防止汇编类型的证人(GenericMethodDemo.<String, Integer>isIn("2", nums))以防止类型推理使用最近的常见超级类型。

可以在此处找到有关类型推理的Java语言规范详细信息:https://docs.oracle.com/javase/javase/specs/jls/se8/html/jls-18.html

相关内容

最新更新