简体   繁体   中英

new ConcurrentHashMap of new ConcurrentHashMap

I'm trying to initialize a ConcurrentHashMap of ConcurrentHashMap s 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 new ly initialized properly?

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM