How to declare a map with variable generics?

前端 未结 2 696
一整个雨季
一整个雨季 2021-01-12 05:50

I have a Map whose keys are of generic type Key, and values are of type List. If the key is an instance of Key

相关标签:
2条回答
  • 2021-01-12 06:21

    This is what you want:

    public class Test<T> extends HashMap<T, List<T>>
    {
    }
    

    If you don't want a HashMap as the super class then change it to whatever concrete class you want.

    0 讨论(0)
  • 2021-01-12 06:41

    I'm not aware of any existing library that does precisely this but it is not too hard to implement yourself. I've done something similar a few times in the past. You cannot use the standard Map interface but you can use a hash map inside to implement your class. To start, it might look something like this:

    public class KeyMap {
      public static class Key<T> { }
    
      private final HashMap<Object,List<?>> values = new HashMap<Object,List<?>>();
    
      public <T> void put(Key<T> k, List<T> v) {
        values.put(k, v);
      }
    
      public <T> List<T> get(Key<T> k) {
        return (List<T>)values.get(k);
      }
    
      public static void main(String[] args) {
        KeyMap a = new KeyMap();
        a.put(new Key<String>(), new ArrayList<String>());
        a.get(new Key<Integer>());
      }
    }
    
    0 讨论(0)
提交回复
热议问题