aspose file tools*
The moose likes Beginning Java and the fly likes is Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "is "String[] str = (String[])ObjArray"" Right?" Watch "is "String[] str = (String[])ObjArray"" Right?" New topic
Author

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

Gary Kevin
Ranch Hand

Joined: Jul 24, 2006
Posts: 43
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?


SCJP 5.0 72%
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Gary Kevin
Ranch Hand

Joined: Jul 24, 2006
Posts: 43
Thanks
vanlalhmangaiha khiangte
Ranch Hand

Joined: Sep 11, 2006
Posts: 170


(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..
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: is "String[] str = (String[])ObjArray"" Right?