| Author |
Reason for ClassCastException
|
praveenkumar kumarpraveen
Greenhorn
Joined: Aug 25, 2005
Posts: 2
|
|
Hi All, Why am I getting class cast exception for the below code? String[] strArray = new String[]{"Hello"}; //1 Vector vectStr = new Vector(); //2 vectStr.addAll(Arrays.asList((Object)strArray)); //3 String getStr = (String) vectStr.get(0); //4 Below is the result Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String at TestClassCast.main(TestClassCast.java:18) if I remove the cast to Object in line //3, it works perfectly. I know I don't need a cast to Object there but I could not understand the reason for exception. Thanks, praveen
|
regards
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Because of the cast and the varargs in Arrays.asList, your array is treated as an array of type Object and size one, with element 0 being the string array. This one element is then added to the Vector. Without the cast, the varargs takes the string array as it is, and adds each string separately being added to the Vector. You could have noticed this if you had used generics on the Vector. Using Vector<String> would have failed because Arrays.asList would have returned List<Object> with the cast. Without the cast it would be List<String>.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
praveenkumar kumarpraveen
Greenhorn
Joined: Aug 25, 2005
Posts: 2
|
|
|
Thanks Rob
|
 |
 |
|
|
subject: Reason for ClassCastException
|
|
|