简体   繁体   中英

Define a recursive definition of a HashMap using generics

Is there a way to define a HashMap that has another HashMap as the value without warning?
I mean if I use generics I would have to define:

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

Is the correct/only way to do it via the followin?

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

Update based on comments:
I am just reviewing generics and I was under the impression that it is not uncommon to have a hashmap as a value of another hashmap.

Update based on @JimGarrison comment:
Using a hash of hashes is a very common structure in other languages so I am surprised that I need to actually give some specific use case in order for my question to make sense. If I need to give a real example that this could be used, one would be to eg navigate through some hierarchical structure. So we could "mimic" a tree.

You might find F-bound types useful, at least from a theoretical point of view. In your case, this might be:

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

Then you could use it this way:

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={}}}

You could only store empty maps at the end, and maps of maps in the middle, so the only practical use I see to this is to store data in the keys (in this case these would be Integer s) and use the values to keep references to children nodes of a tree structure.

Another way would be to let the values be of any type, including HashMap . This way, you could store maps as values of other maps. In this case, you'd need to declare your maps as:

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={}}}

Of course, if you need to get a value, you'd need to cast:

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

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