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

查看:20
本文介绍了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[] 作为参数.

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[] 调用它不是很好吗?

wouldn't it be nice to be able to call it with 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.

你应该总是喜欢 Lists 而不是 arrays,因为 Lists 使用 generics 是不变的.

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

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

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