Java为什么不支持泛型数组? Metadata Author: zhihu.com Full Title: Java为什么不支持泛型数组? Category: articles URL: https://www.zhihu.com/question/20928981/answer/117521433 Highlights 但是!泛型有个什么问题呢?就是泛型是用**擦除(Erasure)**实现的,运行时类型参数会被擦掉。比如下面的例子,无论你声明的的是List<String>,还是List<Integer>或者原生类List,容器实际类型都是List<Object>。 所以泛型实际上都是狼外婆,它看上去像外婆,但实际上是大灰狼。 // 以下三个容器实际类型都是List List strList = new ArrayList(); List intList = new ArrayList(); List rawList = new ArrayList(); 所以数组小鸭子遇到泛型狼外婆就要吃苦头了。对数组小鸭子Object[] 来说,GrandMother<RealGrandMother>和GrandMother<Wolf>运行时看起来都是GrandMother。 那小鸭子岂不是要被吃掉? 所以有正义感的程序员哥哥就禁止掉了这件事。 public static void main(String[] args) { GrandMother[] gm = new GrandMother[3]; // 真外婆 Object[] ducks = gm; // 我们告诉数组小鸭子,只有见到外婆才能开门 ducks[0] = new GrandMother(); // 运行时狼外婆看起来和真外婆一模一样 RealGrandMother rgm = ducks[0].get(); // BOOM! 跳出一只狼外婆,小鸭子懵圈了 } 唯一绕过限制,创建泛型数组的方式,是先创建一个原生类型数组,然后再强制转型。 List[] ga = (List[])new ArrayList[10]; (View Highlight) Note: java不能创建泛型数组的原因。