• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is "String[] str = (String[])ObjArray"" Right?

 
Gary Kevin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:
My Program is:

ArrayList aList = new ArrayList();
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
try{
String[] str = (String[])aList.toArray();
}catch(Exception e)
{
System.out.println(e.getMessage());
}

and it catch an Exception,An Object variable can convert into a String variable just like "String s = (String)Object;",why String Array can't?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An Object variable can convert into a String variable just like "String s = (String)Object;",why String Array can't?

You can only cast an Object reference to a String reference without getting a ClassCastException if the runtime type of the Object is a String.



Similarly with arrays:

[ June 14, 2007: Message edited by: Garrett Rowe ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The toArray() method returns an array of Object. All the elements that are in the array happen, in your case, to be String, but this does not make it an array of String.

Luckily, there is a solution. The toArray(Object[]) method returns an array of the same type as the argument. If you pass it an array of String, it returns an array of String.

See the API for more details.
 
Gary Kevin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
vanlalhmangaiha khiangte
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


(1)If we specify the size of the result String str then this is working..If i don't specify the size then it is not working can anyone tell me why this difference is there?
(2)If i don't pass str,then null is coming..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic