繁体   English   中英

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

[英]Why is this generic method not giving compile-time error?

在此程序中,我正在创建一个泛型方法,其中第二个参数扩展了第一个参数,但是当我将String作为第一个参数传递而将Integer数组作为第二个参数传递时,程序也可以正常运行。 为什么因为Integer不扩展String而没有给出编译时错误?

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

如果我们提供double作为第一个参数,则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/specs/jls/se8/html/jls-18.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM