问题
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?
回答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