| Author |
getting class ClassCastException
|
Rc Reddy
Greenhorn
Joined: Jul 12, 2005
Posts: 5
|
|
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
Joined: Aug 03, 2002
Posts: 7729
|
|
Because it is not a String[], it is an Object[]. Use arrayStr = strList.toArray(new String[0]); instead.
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
Rc Reddy
Greenhorn
Joined: Jul 12, 2005
Posts: 5
|
|
|
Thanks.
|
 |
John Stone
Ranch Hand
Joined: May 04, 2007
Posts: 332
|
|
Rc Reddy: but this one works, can you see why?
|
 |
 |
|
|
subject: getting class ClassCastException
|
|
|