#1 System.out.println(lsint.get(0)); // oracle - OK
#2 for(Object o:lsint); // ClassCastException: String
for(Object o:lsint);
ClassCastException will be thrown. Please checkThis line will not throw any class cast exception.
Output....
C:\jdk1.5.0_12\bin>javac testClass.java
Note: testClass.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\jdk1.5.0_12\bin>java testClass
java.lang.ClassCastException: java.lang.String
at testClass.main(testClass.java:13)
OCPJP 6, OCE JEE 6 JSP and Servlet Developer
I also got the classCastException. I think the error is in here.
List<Integer> lsint = (List<Integer>)obj;
Looks like casting does not happen as you expect. In this line, the elements in obj list has not casted to Integer type.
OCPJP 6, OCE JEE 6 JSP and Servlet Developer
Check carefully. It is because casting has not done for each of object separately in the collection (list) (as we expected).
Simran Dass wrote:
Line #1 works fine - lsint is of type List<Integer> . lsint.get(0) should return an Integer
but it returns a String and is printed. How come there is no ClassCastException.
Henry Wong wrote:
Simran Dass wrote:
Line #1 works fine - lsint is of type List<Integer> . lsint.get(0) should return an Integer
but it returns a String and is printed. How come there is no ClassCastException.
Interestingly, I think line #1 is broken too. If the collection is of type string, then it will return a string and call the println() method that takes a string. However, the compiler thinks it returns Integer and incorrectly routes it to the println() method that takes object. This works at runtime because the println() method that takes object merely calls to string first.
This would have also have failed if there was a method that takes an Integer and does something Integer specific. Or even if autoboxing has taken place.
Henry
SCJP6
A magnificient life is loaded with tough challenges. En garde tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|