Java 带<;的泛型的Instanceof&燃气轮机;还是没有<&燃气轮机;

Java 带<;的泛型的Instanceof&燃气轮机;还是没有<&燃气轮机;,java,generics,instanceof,Java,Generics,Instanceof,我对Java中的泛型和instanceof运算符有一个问题。 不可能进行这样的即时检查: if(arg instanceof List)//由于 //在运行时释放参数 但可以运行这个: if (arg instanceof List<?>) if(arg instanceof List) 现在我的问题来了-在arg instanceof List和arg instanceof List之间有什么区别吗?Java泛型是通过擦除实现的,也就是说,额外的类型信息()在运行时不可用,但

我对Java中的泛型和
instanceof
运算符有一个问题。

不可能进行这样的即时检查:

if(arg instanceof List)//由于
//在运行时释放参数
但可以运行这个:

if (arg instanceof List<?>)
if(arg instanceof List)


现在我的问题来了-
arg instanceof List
arg instanceof List
之间有什么区别吗?

Java泛型是通过擦除实现的,也就是说,额外的类型信息(
)在运行时不可用,但会被编译器擦除。它有助于静态类型检查,但在运行时不起作用

由于
instanceof
将在运行时而不是在编译时执行检查,因此不能在
instanceof…
表达式中检查
Type

至于您的问题(您可能已经知道泛型参数在运行时不可用),
List
List
之间没有区别。后者是一个通配符,基本上表示与不带参数的类型相同的内容。这是告诉编译器“我知道我不知道这里的确切类型”的一种方式


instanceof List
归结为
instanceof List
——它们完全相同

列表和列表<?>
不相同,但在本例中,当您使用withinstanceof运算符时,它们的含义相同

instanceof不能与泛型一起使用,因为泛型在运行时不存储任何类型信息(由于擦除实现)

这一点可以通过下面的主方法来清除。我声明了两个列表(一个是整数类型,另一个是字符串类型)。和instanceof对于
列表和List<?>

public static void main(String[] args){
    List<Integer> l = new ArrayList<Integer>();
    List<String> ls = new ArrayList<String>();

    if(l instanceof List<?>){
        System.out.print("<?> ");
    }

    if(l instanceof List){
        System.out.print("l ");
    }

    if(ls instanceof List<?>){
        System.out.print("<?> ");
    }

    if(ls instanceof List){
        System.out.print("ls ");
    }
     }
publicstaticvoidmain(字符串[]args){
列表l=新的ArrayList();
List ls=新的ArrayList();
if(列表的l实例){
系统输出打印(“”);
}
if(列表的l实例){
系统输出打印(“l”);
}
if(ls instanceof List){
系统输出打印(“”);
}
if(ls instanceof List){
系统输出打印(“ls”);
}
}
输出为:
l ls


在上面的主方法中,所有if语句都为true。所以很明显,在这种情况下,
List和List
是相同的。

是的,我非常清楚这一点,甚至在我的问题@scarvy;中写下了它。)但我的问题是关于其他方面的——仔细阅读(本应仔细阅读)中的编辑内容——我希望现在能回答这个问题?我认为前者可能会在IDE中给你一个警告:“使用了原始类型”(取决于你使用的IDE),而后者不会给你这样的警告。但除此之外,这两者是相同的。泛型实际上只是一个编译器提示,编译器会丢弃它们。好吧,但如果我有泛型类
类a
,据说这样做更好:
a tab[]=new a[2]
,而不是:
a tab[]=new a[2]
,因为在这个示例中,第一个“将至少执行部分类型检查”。部分?你的意思是,检查添加的对象是否至少是instancof对象?这不是什么类型检查……我不是在问执行结果——很明显,它们是相同的,只是关于规则。
instanceof List
只是一个好看的、不做任何额外的语言吗?是的,你完全正确。我只是试着用示例强调同样的问题,因为泛型很容易混淆,所以检查示例有助于:)
public static void main(String[] args){
    List<Integer> l = new ArrayList<Integer>();
    List<String> ls = new ArrayList<String>();

    if(l instanceof List<?>){
        System.out.print("<?> ");
    }

    if(l instanceof List){
        System.out.print("l ");
    }

    if(ls instanceof List<?>){
        System.out.print("<?> ");
    }

    if(ls instanceof List){
        System.out.print("ls ");
    }
     }