简体   繁体   English

Java协变数组不好?

[英]Java covariant array bad?

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. 有几个人告诉我,如果A是B的子类型,Java允许协变数组子类型,那么A []是B []的子类型,但这是一个不好的特性,因为它可能导致运行时错误。 Can someone give me a concrete example to illustrate how it causes runtime errors and if/how does Java address this problem? 有人能给我一个具体的例子来说明它是如何导致运行时错误的,以及Java是否/如何解决这个问题?

Thank you! 谢谢!

Very simple. 非常简单。

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

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

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. 想象一下,你有一个方法将Object []作为参数。

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

wouldn't it be nice to be able to call it with a String[] ? 能用String[]调用它不是很好吗?

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

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. 只要没有任何变异,所有这一切都可以正常工作,Java并没有提供任何保证这一点的机制。

You should always favour Lists over arrays , because Lists use generics which are invariant. 你应该总是喜欢Lists不是arrays ,因为Lists使用不变的generics

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM