• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

getting class ClassCastException

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks.
 
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rc Reddy:
but this one works, can you see why?
 
It was the best of times. It was the worst of times. It was a tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic