简体   繁体   中英

Recursive data type java generic type warnings

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

public HashMap<Character, HashMap> root;

The HashMap s 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!

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>();

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>>();

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.

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