File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes getting class ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "getting class ClassCastException" Watch "getting class ClassCastException" New topic

getting class ClassCastException

Rc Reddy

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(

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.

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

Joined: Jul 12, 2005
Posts: 5
John Stone
Ranch Hand

Joined: May 04, 2007
Posts: 332
Rc Reddy:
but this one works, can you see why?
Consider Paul's rocket mass heater.
subject: getting class ClassCastException
It's not a secret anymore!