Consider the code and output in Eclipse 4.5.0 and javac (1.8) below.
I know that this is related to type-wiping at runtime, but why the second one still outputs data, even if it is declared as List of Integer, I also checked with javap, the checkcast bytecode is inserted only in the third output.
My questions:
This is mistake?
How does javac determine where to insert "cast"?
public static void main(String[] args){ List<String> a = Arrays.asList("abc","def"); List<Integer> b = (List<Integer>)(List<?>)a; System.out.println(b.size()); --output 2 System.out.println(b.get(1)); ---output "def" System.out.println(b.get(1).getClass()); --error in type cast
EDIT
Check the answer below and When is the total return value of a function cast after deleting styles? very similar to my case. If we add an answer from this What is meant by "erasing the static type of the expression it is called from" in getClass () docs? , then it will be clear that such a rule is "cast".
The compiler can determine where to insert the cast and provide type safety.
My first case is fine, as it will return an int anyway.
The second case is fine, since println expects an Object. therefore, no type casting is required to ensure type safety.
The Thrid case does not occur, since it is expected that getClass () returns a class that is the static type b.get (1) according to JLS. Thus, the cast is inserted and receives an error when the type starts.
As @newacct said, “you should not rely on the compiler to decide in any case” (when there is an alternative choice and also provide type safety, the second case is here).
java generics
Keith
source share