Reputation: 1314
I was reading Thinking in Java 4th edition, and in the Chapter Generics, I found these sentences: This paragraph is explaining why array support covariance but generics don't.
The real issue is that we are talking about the type of the container, rather than the type that the container is holding. Unlike arrays, generics do not have built-in covariance. This is because arrays are completely defined in the language and can thus have both compile-time and run-time checks built in,but with generics, the compiler and runtime system cannot know what you want to do with your types and what the rules should be.
but I cannot really understand what this paragraph means, why the compiler know what you want to do with arrays but cannot know what you want to do with generics? can anybody give me any example?
Upvotes: 0
Views: 88
Reputation: 6104
To support legacy code, newer versions of Java allow type-safe code to be used with older code. While creating the bytecode, the Java compiler replaces all the type-safe declarations with relevant casts (casting to Object if no type parameters are present). The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods. This is called Type-erasure. (All of this hassle JUST to support legacy code).
You can find a detailed explanation at my blog here.
Upvotes: 1
Reputation: 12932
First of all, the quote is very unclear. Both arrays and generics are "completely defined in the language", albeit in a different way. And neither the compiler nor the run-time system can read your mind and thus do not know "what you want to do with your types".
The quote seems to refer to the fact that array are reified, while generics are not: at runtime, the element type of a List
is not known, but the element type of an array is. That is: at runtime, both a List<String>
and a List<Integer>
have the same type (a List
), whereas a String[]
and an Integer[]
have different types. At compile time, however, List<String>
and List<Integer>
are different types.
The reason for this is mostly a historical one. Arrays were introduced in the very first version of Java, and there was no reason not to make the element type of an array known at runtime. When generics were introduced in Java 5, however, the goal was to make new Java code compatible with old Java code (and vice-versa), and therefore generics had to be erased at run-time.
Upvotes: 2