views:

119

answers:

4

Given:

Object nestKey;
Object nestedKey;
Object nestedValue;

Map<T,Map<T,T>> nest;
Map<T,T> nested;

How is a mapping added to nested where:

nest.containsKey(nestKey) == true;

?

Or is there an existing library of collections that would be more effective?

A: 

Not sure what you mean. I think you want to add to the nested map like the following:

nest.get(nestKey).put(nestedKey, nestedValue);

This is not possible because the get on outer map returns a map of type Map<?, ?>. You cannot invoke the put method on it. The unbounded wildcard '?' should be used if you don't know the type of a Collection's contents but want to consider them as Objects. If you want to read and modify the contents, and the Map has heterogenous objects, you can just use raw type. That is something like:

Map<?, Map> nest;

Best way of course is (if possible), to use a homogeneous Map and specify its type. Eg. Map<String, String>

You are correct in interpreting what I meant. I meant for this to be generic, I'll change this to using generics as types.
WolfmanDragon
+1  A: 

It is a fairly common idiom to either:

  • have a map of a map as you suggest
  • have one map, where your keys combine "main" key and "subkey" (possibly a more efficient use of space, but generally less suitable if you need to iterate keys and subkeys)
Neil Coffey
combine key and subkey like using multiple keys in SQL to create a primary key, but done with concatenation instead?
WolfmanDragon
A: 

Try this

if (nest.containsKey(nestKey)) { ((Map) nest.get(nestKey)).put(nestedKey, nestedValue); }

Bhushan
+1  A: 

You mean something like the following generic method?

static <U,V,W> W putNestedEntry(
        Map<U,Map<V,W>> nest,
        U nestKey,
        V nestedKey,
        W nestedValue)
{
    Map<V,W> nested = nest.get(nestKey);

    if (nested == null)
    {
        nested = new HashMap<V,W>();
        nest.put(nestKey, nested);
    }

    return nested.put(nestedKey, nestedValue);        
}
Zach Scrivena
I was trying to cheat a way out of setting nested with a nest.get(nestKey). What I was getting ready to do was make a stupid mistake. Thanks for the reality check.
WolfmanDragon