首页 / JAVA / 为什么不能用Java实现泛型数组?
为什么不能用Java实现泛型数组?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了为什么不能用Java实现泛型数组?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2286字,纯文字阅读大概需要4分钟。
内容图文
参见英文答案 > What’s the reason I can’t create generic array types in Java? 15个
Java使用类型擦除
我的理解是将新的ArrayList< String>()转换为其原始类型,并且使用大量的语法糖来假装Object的这个ArrayList就像String的ArrayList一样. Java将此称为类型擦除.
例如
这是我用Java写的:
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("foo");
String s = stringList.get(0);
}
当我反编译字节码时,我得到了这个:
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList();
stringList.add("foo");
String s = (String)stringList.get(0);
}
因此
为什么新的T []不能自动转换为(T [])new Object [],使用编译器为类型擦除提取的相同“shtick”?
请不要向我推荐这个问题:What’s the reason I can’t create generic array types in Java?特别是这个评论:
The problem is deeper than pointed in that answer, so further
investigation is needed. As you said type info is erased and in
compiled code we have no difference between two generic types – all we
have is base type – so why forT[]
– compile toObject[]
. In this case
everything will be fine – array will remember that it was created with
object type and will let save all types. However as for me the real
problem is that arrays are covariant meaning thatAnimal[]
can be
assigned toObject[]
. On the other hand generics are notArrayList<Animal>
can not be assigned toArrayList<Object>
因为这个逻辑是有缺陷的!
这里有两个进程.
>编译器对ArrayList< String>强制执行“人为”不变性.
>编译器将Object转换为T.
同样,为什么不能使用形成所有泛型的简单语法糖在Java中实现泛型数组,同时保持数组的正常协方差?
解决方法:
可以通过两种方式强制执行类型安全:在运行时或编译时.
数组在运行时强制执行:
Object[] array = new Integer[1];
array[0] = "";
// ArrayStoreException!
泛型在编译时强制执行:
List<Object> list1 = new ArrayList<Integer>();
// does not compile!
List<? extends Object> list2 = new ArrayList<Integer>();
list2.add(1);
// does not compile!
因为T []是一个数组,所以它必须是协变的,但由于类型擦除,在运行时没有办法检查类型,如下例所示:
Object[] array = (T[])new Object[1];
array[0] = 1;
由于在运行时数组实际上是Object []类型,因此无论T恰好是什么,此代码都将编译并运行而不会出现错误.这导致heap pollution,这通常会导致您的代码在某个不可预测的地方或时间失败,从而难以诊断和修复.因此警告.
内容总结
以上是互联网集市为您收集整理的为什么不能用Java实现泛型数组?全部内容,希望文章能够帮你解决为什么不能用Java实现泛型数组?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。