Java的协变数组不好? [英] Java covariant array bad?

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

问题描述

我被几个人告诉记者,Java允许换句话说协数组子类型,如果A是B的子类型,那么A []为B []的子类型,但是这是一个坏的功能,因为它可以导致运行错误。有人可以给我一个具体的例子来说明它如何导致运行时错误,如果/如何Java的解决这个问题?

I've been told by several people that Java allows covariant array subtyping in other words if A is a subtype of B, then A[] is a subtype of B[], but that this is a bad feature because it can lead to runtime errors. Can someone give me a concrete example to illustrate how it causes runtime errors and if/how does Java address this problem?

感谢您!

推荐答案

很简单。

String strings[] = {"Broken","Type", "system"};
Object objects[] = strings;

objects[0] = 5; // compiles fine, but throws ArrayStoreException at runtime

协变类型不坏,只要你,你拿的东西,但是你把时刻,整个事情断裂的事情。
想象一下,你有一个方法接受一个Object []作为参数。<​​/ P>

Covariant types are not bad as long as you as you take things out, but the moment you put things in, the whole thing breaks. Imagine you have a method takes an Object[] as a parameter.

fn(Object[]a){
...   
}

那岂不是很高兴能够与叫它的String []

 String[] s = {"I","didn't","know","that","this","was","broken"}
 fn(s);

好吧,听起来自然是能够做到这一点,特别是在早期天的时候,我们并没有在语言仿制药。而这一切工作正常,只要没有得到突变,和Java不提供任何机制来保证。

Well, it sounds natural to be able to do so, especially in the early days when we didn't have generics in the language. And all this works fine as long as nothing get mutated, and Java doesn't provide any mechanism to guarantee that.

您应该总是青睐列表阵列,因为列表使用泛型这是不变的。

You should always favour Lists over arrays, because Lists use generics which are invariant.

这篇关于Java的协变数组不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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