views:

289

answers:

3

I need a dictionary-like data structure that stores information as follows:

key [value 1] [value 2] ...

I need to be able to look up a given value by supplying the key and the value I desire (the number of values is constant). A hash table is the first thing that came to my mind but I don't think it can be used for multiple values. Is there any way to do this with a single datastrucuture rather than splitting each key-value pair into a separate list (or hash table)? Also I'd rather not use a multi-dimensional array as the number of entries is not known in advance. Thanks

A: 

You could make a class that holds the two key values you want to look up, implement equals() and hashcode() to check/combine calls to the underlying values, and use this new class as the key to your Map.

Nate
A: 

I'm not sure what you mean about your list of values, and looking up a given value. Is this basically a keyed list of name-value pairs? Or do you want to specify the values by index?

If the latter, you could use a HashMap which contains ArrayLists - I'm assuming these values are String, and if the key was also a String, it would look something like this:


    HashMap<String, ArrayList<String>> hkansDictionary = new HashMap<String, ArrayList<String>>();

    public String getValue (String key, int valueIdx) {
        ArrayList<String> valueSet = hkansDictionary.get(key);
        return valueSet.get(valueIdx);
    }

If the former, you could use a HashMap which contains HashMaps. That would look more like this:


    HashMap<String, HashMap<String, String>> hkansDictionary 
              = new HashMap<String, HashMap<String, String>>();
    ----
    public String getValue (String key, String name) {
        HashMap<String, String> valueSet = hkansDictionary.get(key);
            return valueSet.get(name);
    }
CPerkins
Thanks..the HashMap of HashMaps is exactly what I was looking for.
hkan1
A: 

I would use

Map<Key,ArrayList<String>> map = new HashMap<Key,ArrayList<String>>

where you define Key as

public class Key{
    private String key;
    private String value;
    //getters,setters,constructor

    //implement equals and hashcode and tostring
}

then you can do

Key myKey = new Key("value","key");
map.get(myKey);

which would return a list of N items

non sequitor