Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getting class ClassCastException

 
Rc Reddy
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; incompatible with [Ljava.lang.String;
at com.test.corejava.util.ArrayTest.main(ArrayTest.java:37)



package com.test.corejava.util;

import java.util.ArrayList;
public class ArrayTest {
public ArrayTest() {
}
public static void main(String[] args) {
String[] arrayStr = null;
String[] arrayStr1 = null;
ArrayList<String> strList = new ArrayList<String>();
strList.add(new String("A"));
strList.add(new String("B"));
strList.add(new String("C"));
strList.add(new String("D"));
strList.add(new String("E"));
strList.add(new String("F"));
strList.add(new String("G"));
arrayStr = new String[strList.size()];
arrayStr = (String[])strList.toArray();
}

}


The above high lighted line throwing Class Cast Exception.
Can you people suggest why is not casting Object[] array to String[] array.

My Understanding is refernce can not cast.


Thanking you inadvance.

Ram
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because it is not a String[], it is an Object[].

Use arrayStr = strList.toArray(new String[0]); instead.
 
Rc Reddy
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rc Reddy:
but this one works, can you see why?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic