构造函数引用 - 创建泛型数组时没有警告
- 论坛
- 构造函数引用 - 创建泛型数组时没有警告
12 浏览
构造函数引用 - 创建泛型数组时没有警告
在Java中,不能直接创建泛型类型的数组:
Test[] t1 = new Test [10]; // 编译错误
然而,我们可以使用原始类型来做到这一点:
Test[] t2 = new Test[10]; // 编译警告 "unchecked"
在Java 8中,还可以使用构造函数引用:
interface ArrayCreator{ T create(int n); } ArrayCreator []> ac = Test[]::new; // 没有警告 Test [] t3 = ac.create(10);
为什么编译器在最后一种情况下不显示警告?它仍然使用原始类型来创建数组,对吗?