Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

casting an object array to string array  RSS feed

 
Rajendra Nath
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
i'm trying to cast an Object array to string array, and it's throwing a class cast exception.

public class example
{
public static void main(String args[])
{
ArrayList arr= new ArrayList();

arr.add("R");
arr.add("A");
arr.add("J");
arr.add("A");

System.out.println("ArrayList size: "+ arr.size());
System.out.println(arr);
String array[]=(String[]) arr.toArray();
System.out.println("array: "+array);
}

}

what may be the reason for an error.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of this:

String array[] = (String[]) arr.toArray();

use this:

String array[] = arr.toArray(new String[arr.size()]);
[ January 11, 2007: Message edited by: Jesper Young ]
 
Muhammad Saifuddin
Ranch Hand
Posts: 1325
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesper Young:

String array[] = arr.toArray(new String[arr.size()]);


I tried this but i receive compiled time error :

Type mismatch: cannot convert from Object[] to String[]
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Saif uddin:

I tried this but i receive compiled time error :

Type mismatch: cannot convert from Object[] to String[]


Try...



Henry
 
Muhammad Saifuddin
Ranch Hand
Posts: 1325
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your fastest reply henry.
now it works fine with error less.

Originally posted by Rajendra Nath:
what may be the reason for an error.
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
if you are using java 1.5, then theres a better way of using collections using templates
create like this
private LinkedList<String> lst = new LinkedList<String>();
if you know for what object types you are going to deal with in advance.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by gaurav abbi:
hi,
if you are using java 1.5, then theres a better way of using collections using templates


The correct term is "generics". "Templates" is how generics are implemented in C++. Java does it differently, using "type erasure".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!