![]() |
HashMap
Hello
I have HashMap with two identical keys, but different values. If do a "get(key name)" on the HashMap Object I don't get both values. I know this how it is supposed to work. The question - is there any data structure in java which will return values for identical keys ? -sanjay |
Re: HashMap
Sanjay Kumar wrote
> I have HashMap with two identical keys, but different values. If do a > "get(key name)" on the HashMap Object I don't get both values. I know this > how it is supposed to work. The question - is there any data structure in java > which will return values for identical keys ? The Map interface do not directly support implementations that map a key to multiple values. However, since values can be any object you like, including other collections, you can perhaps use another Collection inside your Map, like in the following example: public class MyMap { private Map map = new HashMap(); public void add(Object key, Object value) { Collection values = get(key); if (values == null) { values = new HashSet(); // use whatever collection makes sense map.put(key,values); } values.add(value); } public void remove(Object key, Object value) { Collection values = get(key); if (values == null) return; values.remove(value); if (values.isEmpty()) { map.remove(key); } } public Collection get(Object key) { return (Collection) map.get(key); } // delegate to other map methods as needed ... } So, with MyMap myMap = new MyMap(); myMap.add(key,value1); myMap.add(key,value2); you can iterate now over the elements for key by doing Iterator i = myMap.get(key).elements(); while (i.hasNext()) { Object myValue = i.next(); } -- Filip Larsen |
Re: HashMap
Thanks for all the ideas !!
-sanjay nd81@hotmail.com (Sanjay Kumar) wrote in message news:<99793c86.0307040702.17baf8e0@posting.google. com>... > Hello > > I have HashMap with two identical keys, but different values. If do a > "get(key name)" on the HashMap Object I don't get both values. I know this > how it is supposed to work. The question - is there any data structure in java > which will return values for identical keys ? > > -sanjay |
| All times are GMT. The time now is 04:08 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.