Question

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.

Was it helpful?

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

OTHER TIPS

Its a really bad idea which you are tying to do. But you can do as below.

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

In this case below line will fail.

allInOne.put("total", 0.0); 

But these two lines compile

allInOne.put("", new ConcurrentHashMap<String, Object>());
allInOne.get("").put("total", 0.0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top