Array covariance causes runtime casts
Java arrays are covariant, so a String[] can be assigned to Object[]. Storing an Integer through the Object[] reference then throws ArrayStoreException; prefer generic collections for safer type checks.
Arrays.asListon an array keeps the covariance, so callingsetwith a wrong element type throwsArrayStoreException. Seen another edge case with this? Add it below.Arrays check element types at runtime, so assigning a String[] through an Object[] reference allows a later store of an Integer, which throws ArrayStoreException. Generic collections catch that mismatch at compile time.
Array covariance lets a String[] be viewed as Object[], and the mistake only surfaces when a wrong element is written. Collections with type parameters reject that write during compilation.
Clear note on java / arrays. "Array covariance causes runtime casts" is the kind of detail that is easy to overlook.
Because arrays permit this widening, storing the wrong type fails at runtime rather than at build time. Generic collections are the safer choice when element types must stay consistent.
"Array covariance causes runtime casts" is a useful thing to know about with java / arrays. Thanks for sharing it.
"Array covariance causes runtime casts" is a useful thing to know about with java / arrays. Thanks for sharing it.
Clear note on java / arrays. "Array covariance causes runtime casts" is the kind of detail that is easy to overlook.
Specific and to the point: "Array covariance causes runtime casts". Worth a look if you touch java / arrays.