Search code examples
javatemplatesobjectcastingconcurrenthashmap

accessing a ConcurrentHashMap of Objects that can be ConcurrentHashMaps


I'm trying to hold data in one dynamic container for productivity's sake.

I initialize it inside a class with

private final ConcurrentHashMap<String, Object> allInOne = 
    new ConcurrentHashMap<String, Object>();

allInOne.put("total", 0.0); works without error.

allInOne.put(account, new ConcurrentHashMap<String, Object>()); works without error.

allInOne.get(account).put("total", 0.0); makes javac give:

DynamicConcurrentHashMapper.java:162: error: cannot find symbol
        allInOne.get(account).put("total", 0.0);
                              ^
symbol:   method put(String,double)
location: class Object

I've seen How do I access nested HashMaps in Java?, and I'm happy to have a solution, but is there any way to do it without casting? If not, is there a better way to template allInOne?


Special Case

I agree with all that this is bad practice for strict atomicity and recommend against it to others, but I'm trying to get a working prototype done as soon as possible.


Solution

  • you need to explicitly cast the allInOne.get(account) to ConcurrentHashMap<String, Object>()

    do like this.

    ConcurrentHashMap<String, Object> accountMap = (ConcurrentHashMap<String, Object>)allInOne.get(account);