I have a HashMap with Key, Value pairs.I wanted to create a String array of Values in that HashMap.So I created a set of Values using keySet() method. Then I used toArray() method on the set.Now I have Array of Objects.
Now I looped through the object array and explicitly casted every object in that array to String.
Is this a correct way of doing this? If not, please suggest any other sophisticated way.
I think nothing's wrong with that. But here's a clearer way.
The toArray() method of a Set interface is overloaded, it has a version wich takes an initialized array as a parameter and puts all of the set members into this array. The array type must conform to the generic type of the set, so you won't need any type converting. Here's an example of using this method:
the code posted form Serge is correct, if you compile and run it you will see that it works. About the method toArray(T) API- DOC says:
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.
And the String array allocated before is big enought to contain all the keys of the map, so it's not necessary to use the return type.
SCJP 6.0 [95%] OCE EJBD 6.0 [93%]
Joined: Aug 13, 2007
Mighty stupid of me to assume the code doesn't work based on the docs .. and misinterpreting them as well.
I take back my last post and my apologies Serge ...
Joined: Oct 19, 2007
Thank you all for letting me know the better way of doing what I want.