| Author |
Problems in converting ArrayList to a Strin gArray
|
JT Reddy
Greenhorn
Joined: Jan 31, 2006
Posts: 4
|
|
Dear All, ------------------ //pNames is an ArrayList & contains 2 String objects String[] pNames_strArray = (String[]) pNames.toArray(); //not working ------------------ I want to convert ArrayList to a string array, but I am getting ClassCastException. What is the right way to do it. TIA
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24061
|
|
The version of toArray() that takes no arguments will always return an Object[]. If you want (for example) a String[], then you need to pass a String[] in as an argument. It can be any length, but if you're allocating one anyway, make it the right size and then toArray will use the one you pass in. So... String[] pNames_strArray = (String[]) pNames.toArray(new String[pNames.size()]); This is so common that many IDEs let you type this whole line with one keystroke.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
|
|
Originally posted by Ernest Friedman-Hill: The version of toArray() that takes no arguments will always return an Object[]. If you want (for example) a String[], then you need to pass a String[] in as an argument. It can be any length, but if you're allocating one anyway, make it the right size and then toArray will use the one you pass in. So... String[] pNames_strArray = (String[]) pNames.toArray(new String[pNames.size()]); This is so common that many IDEs let you type this whole line with one keystroke.
Actually if you do it the way Ernest suggests, you don't need the cast at all: String[] pNames_strArray = (String[]) pNames.toArray(new String[pNames.size()]); becomes: String[] pNames_strArray = pNames.toArray(new String[pNames.size()]);
|
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24061
|
|
In Tiger, that is. In JDK 1.4 and earlier, you still need the cast. [ February 03, 2006: Message edited by: Ernest Friedman-Hill ]
|
 |
JT Reddy
Greenhorn
Joined: Jan 31, 2006
Posts: 4
|
|
|
Thanks a lot for the input.
|
 |
 |
|
|
subject: Problems in converting ArrayList to a Strin gArray
|
|
|