Java嵌套Map声明 - 内部Map具体类型

时间:2016-05-11 10:15:27

标签: java java-7

我有一张如下所示的地图foo

private final Map<String, Map<String, Bar>> foo = new ConcurrentSkipListMap<String, Map<String, Bar>>();

由于我不希望数据类型看起来暴露具体数据类型,所以我没有将其声明为:

private final Map<String, ConcurrentSkipListMap<String, Bar>> foo = new ConcurrentSkipListMap<String, ConcurrentSkipListMap<String, Bar>>();

我的问题是内部地图的实际类型是什么?如果我想要内部地图与外部地图相同的类型(ConcurrentSkipListMap)。如何在不暴露具体数据类型的情况下进行此操作?

1 个答案:

答案 0 :(得分:1)

You've declared the outer map as Map as opposed to ConcurrentSkipListMap to hide it's implementation - you can do just the same with the inner map.

The (outer) map you've created is empty - the only known thing about it is that it maps String to Map (any class implementing Map), therefore your question is wrong - there is no actual inner map (not yet, anyway) and the only thing you know about it without any checks is that it's a Map<String, Bar>

It's worth noting that unless you have very specific requirements that mandate usage of specific implementations, you should be using interfaces to declare variables.