在实例化 ArrayLists 时,我习惯于看到这样的代码
ArrayList<Type> arr = new ArrayList<Type>();
或
ArrayList<Type> arr = new ArrayList<>();
但是今天我遇到了一个 ArrayList 的实例,它看起来像这样:
ArrayList<Type> arr = new <Type>ArrayList();
发生了什么,为什么会给出“不安全操作”编译警告?
最佳答案
编辑:
是的,找到了引用。见 JLS §15.12.2.1 - Identify Potentially Applicable Methods :
If the method invocation includes explicit type arguments, and the member is a generic method, then the number of type arguments is equal to the number of type parameters of the method.
- This clause implies that a non-generic method may be potentially applicable to an invocation that supplies explicit type arguments. Indeed, it may turn out to be applicable. In such a case, the type arguments will simply be ignored.
强调我的。
另见 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()
是一种非泛型方法。
关于java - 为什么为非泛型方法或构造函数提供显式类型参数会编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22174022/