简体   繁体   中英

Using HashMap as Collection in Java

JAXB doesn't let you unmarshal already existing xml structures into HashMap s if they are not exactly the way JAXB expects them.

JAXB is fine with handling eg LinkedList s and filling them.

I was thinking of creating a interface with a getKey() method and a wrapper around the HashMap taking all objects that implement that interface. The wrapper can then use the getKey() method for all key related features of the map. The wrapper could then easily implement the Collection or List interface.

Because this idea doesn't seem to innovative to me I presume that it already exists in some package, but I'm not googling correctly for it... Can someone please name a good lib that can do this, or do I have to code this myself?

You might consider extending ForwardingList of guava, and using a HashMap in the back. I don't know of any implementation that will leave you only the actual mapping.
Another alternative is creating JAXB XmlAdapter to adapt the values to your map. I think this one is more appropriate.

If all you are trying to pass the information content of a Map as a Collection , use Map.entrySet() . That gives you a Set<Map.EntrySet<K,V>> object; ie a collection whose elements are the key/value pairs of the Map . To reconstruct a Map from the collection, you will need to iterate the set and perform an put for each element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM