编辑:
是的,找到了参考。见JLS §15.12.2.1 - Identify Potentially Applicable Methods:
如果方法调用包含显式类型参数,并且
member 是泛型方法,则类型参数的数量相等
到方法的类型参数个数。
- 该条款暗示了一个非泛型方法可能是潜在的
适用于提供显式类型参数的调用。
事实上,它可能会被证明是适用的。 在这种情况下,类型
参数将被忽略。
强调我的。
另请参阅JLS §15.9.3 - Choosing the Constructor and its Arguments,了解如何解析构造函数调用。它还提到要遵循上述过程进行解决。
原答案:
当您有一个泛型构造函数并且编译器无法推断出正确的类型参数时,通常需要这种调用。例如,考虑下面的代码:
class Demo<T> {
public <X> Demo(X[] arg1, X arg2) {
// initialization code
System.out.println(arg1.getClass());
System.out.println(arg2.getClass());
}
}
假设你像这样调用构造函数:
Demo<String> demo = new Demo<String>(new String[2], new Integer(5));
你会认为类型推断应该失败,因为类型参数应该具有相同的类型。这里我们传递String 和Integer 类型。但事实并非如此。编译器将X 类型推断为:
Object & Serializable & Comparable<? extends Object&Serializable&Comparable<?>>
现在,您可能希望将类型参数推断为 Object,然后在这种情况下,您可以提供显式类型参数,如下面的代码所示:
Demo<String> demo = new <Object>Demo<String>(new String[2], new Integer(5));
这类似于在方法调用时给出显式类型参数。
现在,在您的代码中,您已经给出了显式类型参数,但您使用类的原始类型来实例化它:
ArrayList<Integer> arr = new <String>ArrayList();
<String> 是构造函数的显式类型参数,编译器可以使用它。但问题是,您正在实例化原始类型ArrayList,这就是编译器发出未经检查的警告的地方。如果您将该代码更改为:
ArrayList<Integer> arr = new <String>ArrayList<>();
警告将消失。但是由于ArrayList构造函数不是泛型构造函数,类型参数似乎只是被构造函数忽略了。实际上,那里没有使用该类型参数。
奇怪的是,这也可以编译:
public static void test() { }
public static void main(String... args) {
Main.<Integer>test();
}
...尽管test() 是一个非泛型方法。