泛型中的数组类型 [英] Array type in generics

查看:27
本文介绍了泛型中的数组类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个泛型数组.我收到错误:

I am trying to create an array of generic type. I am getting error:

 Pair<String, String>[] pairs;   // no error here

 pairs = new Pair<String, String>[10];   // compile error here

 void method (Pair<String, String>[] pairs)  // no error here.

我很困惑.为什么会发生这种情况的任何线索.

I am confused. Any clues why this is happening.

推荐答案

这背后的原因是你不能创建泛型或参数化类型的数组,只能创建 reifiable 类型(即可以在运行时推导).

The reason behind this is that you can't create arrays of generic or parameterized types, only reifiable types (i.e. types which can be deduced at runtime).

虽然可以声明这样的数组类型作为变量或方法参数.这有点不合逻辑,但 Java 现在就是这样.

It is possible though to declare such array types as variables or method parameters. This is a bit illogical, but that's how Java is now.

Java 泛型和集合在第 6 章中广泛讨论了这个问题和相关问题.

Java Generics and Collections deals with this and related issues extensively in chapter 6.

这篇关于泛型中的数组类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆