I would consider this compiler error in javac . The checked listing rises. We can see this using javap -c CheckRawTypeAdd to parse the class (cast is 101; note that before compiling I extracted some unnecessary lines of code, so the code points will change):
77: invokeinterface
However, the Java Language Spec (14.14.2) indicates that this cast should be an Object , not an Integer . It begins by defining terms through grammar:
EnhancedForStatement: for ( FormalParameter : Expression ) Statement FormalParameter: VariableModifiersopt Type VariableDeclaratorId VariableDeclaratorId: Identifier VariableDeclaratorId []
So, in our case, Type is Object . Then he goes on to say what this means:
for (I
So the permission of TargetType appropriate here. This is also defined in JLS:
If the type (in the form of FormalParameter) is a reference type, then TargetType is Type
Since Object is most likely a reference type, then TargetType is Object , and so the checked listing should be Object , not Integer .
That this is a mistake is confirmed again by others in this thread, noting that this problem does not occur if ecj (Eclipse compiler) is used. However, I understand that this will be a low-priority error for the Oracle compiler command, since you must abuse generics to use it. One could almost say that this is a feature, not a mistake.
Subsequent
To give definitive confirmation that this is an error, there is an error report for this exact problem:
In addition, I must note two things. First , the JLS links above were in the last JLS, and this section has actually changed for Java 7 (in response to this error!)
Here's what advanced operator should translate to for Java 6 and earlier:
for (I
As you can see, test casting is not indicated here. Thus, the error in javac was not that he did the wrong translation, but that he performed any cast .
Second , in Java 7, javac correctly compiles code in accordance with the JLS SE 7 specification (this is what I cited above). Thus, the following code works:
List<String> list_str = new ArrayList<String>(); ((List) list_str).add(new StringBuilder(" stringbuilder")); for (CharSequence o : list_str) { System.out.println("o value is" + o); }
When pressed CharSequence , CharSequence , not String . I used JDK 6 first, not JDK 7.