问题描述
考虑Java的 ArrayList#toArray
方法的以下测试。请注意,我借用了这个有用的中的代码。
Consider the following test of Java's ArrayList#toArray
method. Note that I borrowed the code from this helpful answer.
public class GenericTest {
public static void main(String [] args) {
ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(2);
foo.add(3);
foo.add(4);
foo.add(5);
Integer[] bar = foo.toArray(new Integer[10]);
System.out.println("bar.length: " + bar.length);
for(Integer b : bar) { System.out.println(b); }
String[] baz = foo.toArray(new String[10]); // ArrayStoreException
System.out.println("baz.length: " + baz.length);
}
}
但是,请注意会有 ArrayStoreException
尝试将 Integer
放入 String []
时。
But, notice that there will be a ArrayStoreException
when trying to put an Integer
into a String[]
.
输出:
$>javac GenericTest.java && java -cp . GenericTest
bar.length: 10
1
2
3
4
5
null
null
null
null
null
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.ArrayList.toArray(Unknown Source)
at GenericTest.main(GenericTest.java:16)
在编译时可以通过Java泛型防止此错误吗?
Can this error be prevented through Java generics at compile-time?
推荐答案
ArrayStoreException
正是因为Java的类型系统无法正确处理这种情况(IIRC,当Generics出现时,以与集合框架相同的方式改造数组为时已晚)。
ArrayStoreException
exists precisely because Java's type system cannot handle this situation properly (IIRC, by the time Generics came along, it was too late to retrofit arrays in the same manner as the collections framework).
因此,在编译时通常无法阻止此问题。
So you can't prevent this problem in general at compile time.
您当然可以创建内部API来包装此类操作,以减少意外错误输入类型的可能性。
You can of course create internal APIs to wrap such operations, to reduce the likelihood of accidentally getting the types wrong.
参见:
- Dealing with an ArrayStoreException
- Why are arrays covariant but generics are invariant?
这篇关于在编译时捕获ArrayStoreException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!