HashMap

S

Sanjay Kumar

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
 
F

Filip Larsen

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();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top