new ConcurrentHashMap of new ConcurrentHashMap

孤街醉人 提交于 2020-01-06 12:42:13

问题


I'm trying to initialize a ConcurrentHashMap of ConcurrentHashMaps with

private final ConcurrentHashMap<
    String, 
    ConcurrentHashMap<String, Double>
> myMulitiConcurrentHashMap = new ConcurrentHashMap<
    String, 
    new ConcurrentHashMap<String, Double>()
>();

but javac gives

HashMapper.java:132: error: illegal start of type
    new ConcurrentHashMap<String, Double>()
    ^
HashMapper.java:132: error: '(' or '[' expected
    new ConcurrentHashMap<String, Double>()
        ^
HashMapper.java:132: error: ';' expected
    new ConcurrentHashMap<String, Double>()

pointing to the second new.

How can myMulitiConcurrentHashMap be newly initialized properly?


回答1:


By the way, Java 7 has a more concise syntax now (the "diamond"):

private final 
   ConcurrentHashMap<String, ConcurrentHashMap<String, Double>>
      myMulitiConcurrentHashMap =
         new ConcurrentHashMap<>();

You should be able to use interfaces on the left hand side, too:

private final 
   ConcurrentMap<String, ConcurrentMap<String, Double>>
      myMulitiConcurrentHashMap =
         new ConcurrentHashMap<>();



回答2:


You do not initialize the inner ConcurrentHashMap<String, Double>; just the following should work:

new ConcurrentHashMap<
    String, 
    ConcurrentHashMap<String, Double>
>();



回答3:


Generic type parameters are exactly that – types.
It doesn't make sense to have a Map<String, new SomeType()>.
You need to simply write the type of the second parameter.

To paraphrase, you're creating a single new ConcurrentHashMap<K, V>(), which can hold multiple inner maps later.



来源:https://stackoverflow.com/questions/20318655/new-concurrenthashmap-of-new-concurrenthashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!