Recursive data type java generic type warnings

258 views Asked by At

I'm trying to make a recursive HashMap data structure as such:

public HashMap<Character, HashMap> root;

The HashMaps inside of root are also of type <Character, HashMap>. This throws raw type warnings because the HashMap inside is not parametrized. I can't think of a way to do away with these warnings, because any attempts to explicitly parametrize a HashMap will not stop because of its recursive nature. Any suggestions?

Thanks!

3

There are 3 answers

0
Lodewijk Bogaards On BEST ANSWER

Declare:

class MyHashMap extends HashMap<Character, MyHashMap> { }

Define:

MyHashMap root;

Generalized form:

Declare interface:

interface RecursiveMap<K> extends Map<K, RecursiveMap<K>> { }

Declare implementations:

class RecursiveHashMap<K> extends HashMap<K, RecursiveMap<K>> implements RecursiveMap<K> { }

class RecursiveTreeMap<K> extends TreeMap<K, RecursiveMap<K>> implements RecursiveMap<K> { }

Define:

RecursiveMap<Character> root  = new RecursiveHashMap<Character>();

RecursiveMap<Character> root2 = new RecursiveTreeMap<Character>();
4
Braj On

It you are not sure about generic type of inner Map then use below code.

Always use interfaces for declaration.

If in future you want to change root of type TreeMap then you can do it easily.

Map<Character, Map<Character,Object>> root=new  HashMap<Character, Map<Character,Object>>();
0
Sid On

I don't think it will be wisable to have recursive Map because at any given point of time , you might want to have some kind of object type different than the Map, or else it would be of infinte depth (making no sense). Try using:

  1. Map<Character, Map<Character, Object>, OR
  2. Use a Class to hold a Map and Recursively store the class.