为什么Java允许类型不安全的阵列分配? [英] Why does Java allow type-unsafe Array assignments?

查看:196
本文介绍了为什么Java允许类型不安全的阵列分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,Java可以被视为类型安全的语言。我知道泛型有一些缺陷,但我最近遇到了一个前所未有的问题。
要分解:

Generally, Java can be considered as a type-safe language. I know that there are some flaws with generics, but I recently came across a Problem I never had before. To break it down:

Object[] objects = new Integer[10];
objects[0] = "Hello World";

不会导致编译时错误。我假设一个 Object 数组的声明将不允许指向其他数组。在泛型中,我不允许做出如下奇怪的事情:

will NOT result in a compile-time error as expected. I would assume that the declaration of an Array of Object will disallow to point to to an array of something else. In Generics I'm not allowed to make such weird things like:

ArrayList<Object> objs = new ArrayList<Integer>

如果我试图用Java来欺骗Java做什么

and if I try to kind of trick Java into doing something with

ArrayList<? extends Object> objects = new ArrayList<Integer>

我可以申报,但我只能添加空。

I'm allowed to declare it, but I can only add Objects of type null.

为什么Java不会阻止声明这样的数据呢?

Why doesn't Java prevent the declaration of such weired arrays?

推荐答案

除了遗留设计之外,我认为没有答案。 (我承认这是一种说因为的奇特方式。)你几乎需要能够做一些你以某种方式显示的最后一个作业。 (否则你会坚持使用手动上/下模型制作大量的副本,假设Java 1.4的语言特性)

I don't think there's an answer to this besides "legacy design". (Which I admit is a fancy way of saying "because".) You pretty much need to be able to do an equivalent of the last assignment you show somehow. (Otherwise you're stuck to making lots and lots of copies with manual up/down casts, assuming language features of Java pre 1.4)

在Java 1中,当类型语义为数组基本上是一成不变的,泛型不可用,甚至还有很长时间才考虑。因此,没有任何机制可用于表达使此构造类型安全所需的高阶类型约束 - 而Gosling(IIRC简单的粉丝)认为解决编译时类型安全的边缘情况并不值得复杂化语言无论有哪种解决方案。或者没有在运行时进行足够的检查以寻找解决方案。 (在一天结束时,语言设计决策至少在某种程度上是任意的,并且只有一个人可以肯定地回答这个问题。)

In Java 1 when type semantics for arrays were basically set in stone, generics weren't available, or even up for consideration for a long while yet. So there was no mechanism available to express the higher-order type constraints needed to make this construct type-safe – and Gosling (IIRC a fan of simplicity) felt resolving this edge case of compile-time type safety wasn't worth complicated the language with whichever solutions were available. Or wasn't bothered by doing the check at runtime enough to even look for a solution. (At the end of the day language design decisions are arbitrary to at least some degree, and there's only one person that could answer this with any certainty.)

这篇关于为什么Java允许类型不安全的阵列分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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