• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reason for ClassCastException  RSS feed

 
praveenkumar kumarpraveen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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>.
 
praveenkumar kumarpraveen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!