wood burning stoves 2.0*
The moose likes Java in General and the fly likes How to get an array out of a Map? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "How to get an array out of a Map?" Watch "How to get an array out of a Map?" New topic
Author

How to get an array out of a Map?

Dave Mulligan
Greenhorn

Joined: Mar 14, 2003
Posts: 18
OK, this is one of those things that sounds like it should be simple, but I'm just being blind. Feel free to start any (helpful) answer with "as should be obvious to any intelligent lifeform..."
I have a HashMap of Address objects, with Strings as the keys. I want to extract an array of Address objects from it. So I tried

but that throws an ArrayStoreException. I think that this is because the Set that is returned by the entrySet() method contains Map.Entry objects, not Address objects but that hasn't helped me work out how to get the contents as an Address[] array.
Any help gratefully accepted
Dave
Dave Mulligan
Greenhorn

Joined: Mar 14, 2003
Posts: 18
Oh dear, now I'm embarrassed. Try values() intead of entrySet() :roll:
Should have been obvious to any intelligent lifeform with a reference book.
Dave
Angel Dobbs-Sciortino
Ranch Hand

Joined: Sep 10, 2003
Posts: 101
I think the problem is that HashMap.values() returns a Collection, which is an interface. In this code, I'm using an ArrayList. I don't have a java compiler on hand to test this, but try this:
Address[] myAddressArray = (Address[]) ArrayList(addresses.values()).toArray()
Angel
 
GeeCON Prague 2014
 
subject: How to get an array out of a Map?