使用泛型定义HashMap的递归定义

时间:2016-03-11 22:28:43

标签: java generics data-structures hashmap

有没有办法定义一个HashMap,其中有另一个HashMap作为值而没有警告?
我的意思是,如果我使用泛型,我将不得不定义:

HashMap<Integer, HashMap<Integer, HashMap<Integer, HashMap<Integer,HashMap etc>> map = new HashMap<>();  

通过以下方式进行正确/唯一的方式吗?

HashMap<Integer, HashMap> map = new HashMap<Integer, HashMap>();  

根据评论进行更新
我只是在审查泛型,我的印象是将hashmap作为另一个hashmap的值并不常见。

根据@JimGarrison评论更新评论:
使用散列哈希是其他语言中非常常见的结构,所以我很惊讶我需要实际给出一些特定的用例以使我的问题有意义。如果我需要给出一个可以使用它的真实例子,那就是例如浏览一些分层结构。所以我们可以“模仿”一棵树。

1 个答案:

答案 0 :(得分:2)

至少从理论的角度来看,你可能会发现F-bound types很有用。在您的情况下,这可能是:

class FBoundedMap<K> extends HashMap<K, FBoundedMap<K>> {
}

然后你可以这样使用它:

FBoundedMap<Integer> map = new FBoundedMap<>();

FBoundedMap<Integer> inner1 = new FBoundedMap<>();
map.put(1, inner1);

FBoundedMap<Integer> inner2 = new FBoundedMap<>();
map.put(2, inner2);

FBoundedMap<Integer> innerMost1 = new FBoundedMap<>();
inner1.put(11, innerMost1);

FBoundedMap<Integer> innerMost2 = new FBoundedMap<>();
inner2.put(22, innerMost2);

System.out.println(map); // {1={11={}}, 2={22={}}}

你最后只能存储空地图,中间存储地图,所以我看到的唯一实际用途是将数据存储在密钥中(在这种情况下,这些将是Integer s并使用这些值来保持对树结构的子节点的引用。

另一种方法是让值为任何类型,包括HashMap。这样,您可以将地图存储为其他地图的值。在这种情况下,您需要将地图声明为:

Map<Integer, Object> map = new HashMap<>();

Map<Integer, Object> inner1 = new HashMap<>();
map.put(1, inner1);

Map<Integer, Object> inner2 = new HashMap<>();
map.put(2, inner2);

Map<Integer, Object> innerMost1 = new HashMap<>();
inner1.put(11, innerMost1);

Map<Integer, Object> innerMost2 = new HashMap<>();
inner2.put(22, innerMost2);

System.out.println(map); // {1={11={}}, 2={22={}}}

当然,如果你需要获得一个值,你需要施放:

Map<Integer, Object> value = (Map<Integer, Object>) map.get(1);
System.out.println(value); // {11={}}