1

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.

Community
  • 1
  • 1
  • 2
    Don't do that; it's a bad idea. And it's also extremely difficult to make it properly thread-safe. – SLaks Dec 02 '13 at 01:11
  • @SLaks Thank-you! Yes, I know it's bad practice, but I'd like to have a working prototype now and clean it up later. Can you offer a suggestion? Thank you so much in advance! –  Dec 02 '13 at 01:12

2 Answers2

2

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);
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

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);
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
  • Thank-you! Yes, strict templating won't work in my case. Can you think of an alternative that doesn't involve templating and casting? Thank you so very much in advance! –  Dec 02 '13 at 01:19
  • @Gracchus this is better solution than my answer. – Prabhakaran Ramaswamy Dec 02 '13 at 01:21
  • No I don't. Do you have any valid reasons not using Generics or Casting? – Jayamohan Dec 02 '13 at 01:22
  • @Jayamohan Speed of coding. I just want a working prototype for a loose proof of concept of sorts. Once I'm finished with that, I will definitely rework the code to the best practices all here recommend. –  Dec 02 '13 at 01:23