Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Java (http://www.velocityreviews.com/forums/f30-java.html)
-   -   HashMap (http://www.velocityreviews.com/forums/t124056-hashmap.html)

Sanjay Kumar 07-04-2003 03:02 PM

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

Filip Larsen 07-04-2003 04:02 PM

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



Sanjay Kumar 07-05-2003 07:10 PM

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.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57