Array Covariance Throws ArrayStoreException
Assign a String[] to an Object[] alias and store an Integer to trigger ArrayStoreException at runtime while the original array stays intact.
Code
import java.util.Arrays;
public class ArrayCovariance {
public static void main(String[] args) {
String[] strings = { "valid", "also valid" };
// 协变 (covariance):String[] 可以赋给 Object[] 引用,编译期放行
Object[] alias = strings;
try {
alias[0] = 42; // 真实元素类型是 String:运行时抛 ArrayStoreException
System.out.println("unreachable");
} catch (ArrayStoreException e) {
System.out.println("store rejected: " + e.getClass().getSimpleName());
}
// 非法写入不会破坏原数组:异常在元素真正落位前抛出
System.out.println("array intact: " + Arrays.toString(strings));
// 泛型集合是不变的:List<Object> l = new ArrayList<String>() 编译期就拒绝
System.out.println("prefer List<...> for compile-time checks");
}
}Array Covariance Throws ArrayStoreException: how the code works
The code’s whole job belongs to the class ArrayCovariance and the function main.
Watch out for
- Each symbol comes from the language core; nothing to fetch.
Using it
Signature: public static void main(String[] args)
Watch for the unreachable, store rejected:, array intact: prefixes in the run output — each one names the step that printed it.
Key statements
alias[0] = 42; // 真实元素类型是 String:运行时抛 ArrayStoreException
System.out.println("unreachable");
String[] strings = { "valid", "also valid" };
Object[] alias = strings;
Interactive Tools for This Topic
FAQ
- What does Array Covariance Throws ArrayStoreException print when run?
- Execute the whole file; each printed line is prefixed with a label like `unreachable`, `store rejected:`, `array intact:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.