I understand what an ArrayStoreException is. My question is: why isn’t this caught by the compiler?
This might be an odd example, but say you do this:
HashMap[] h = new LinkedHashMap[4];
h[0] = new PrinterStateReasons();
Why can’t the compiler recognize that this isn’t valid?
Because the information you’ve given the compiler allows what you’re doing. It’s only the runtime state that’s invalid. Your
hvariable is declared as being aHashMap[], which means that as far ashis concerned, anything implementingHashMapis a valid element.PrinterStateReasonsimplementsHashMap, and soh[0] = new PrinterStateReasons();is a perfectly valid statement. Similarly, sinceLinkedHashMapimplementsHashMap, the statementHashMap[] h = new LinkedHashMap[4];is a perfectly valid statement. It’s only at runtime that you try to store aPrinterStateReasonsobject as an element in aLinkedHashMaparray, which you can’t do as it isn’t assignment-compatible.The two statements you’ve given are contiguous, but of course the generalized reality is far more complex. Consider: