我明白 ArrayStoreException 是什么。我的问题是:为什么这不被编译器捕获?
这可能是一个奇怪的例子,但假设你这样做:
HashMap[] h = new LinkedHashMap[4];
h[0] = new PrinterStateReasons();
为什么编译器不能识别这是无效的?
最佳答案
因为您提供给编译器的信息允许您正在做的事情。只有运行时状态是无效的。您的 h
变量被声明为 HashMap[]
,这意味着就 h
而言,任何实现 HashMap
是有效元素。 PrinterStateReasons
实现了 HashMap
,因此 h[0] = new PrinterStateReasons();
是一个完全有效的语句。类似地,由于 LinkedHashMap
实现了 HashMap
,语句 HashMap[] h = new LinkedHashMap[4];
是一个完全有效的语句。只有在运行时,您才尝试将 PrinterStateReasons
对象作为元素存储在 LinkedHashMap
数组中,但您不能这样做'分配兼容。
您给出的两个陈述是连续的,但当然普遍的现实要复杂得多。考虑:
HashMap[] h = foo.getHashMapArray();
h[0] = new PrinterStateReasons();
// ... elsewhere, in some `Foo` class -- perhaps compiled
// completely separately from the code above, perhaps
// even by a completely different team and even a different
// compiler -- and only combined with the code above at runtime...
public HashMap[] getHashMapArray() {
return new LinkedHashMap[4];
}
关于java - 为什么 ArrayStoreExceptions 不能被 Java 编译器捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8379080/