如何声明具有变量泛型的地图? [英] How to declare a map with variable generics?

查看:134
本文介绍了如何声明具有变量泛型的地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Map ,其密钥是通用类型 Key< T> ,值为code>列表与LT; T> 。如果密钥是 Key< String> 的实例,则该值必须为 List< String> ,而相同的规则适用于任何其他键值对。我尝试过以下操作,但不编译:

I have a Map whose keys are of generic type Key<T>, and values are of type List<T>. If the key is an instance of Key<String>, the value must be a List<String>, and the same rule applies to any other key-value pairs. I have tried the following but it does not compile:

Map<T, List<T>> map;

目前我必须用partial泛型声明:

At present I have to declare it with "partial" generics:

Map<Object, List> map;

我知道这是坏的,但我目前没有更好的选择。在这种情况下可以使用泛型吗?

I know this is bad but I currently have no better choice. Is it possible to use generics in this situation?

更新

也许我没有明确表达我的问题。我想要一个地图:

Maybe I didn't express my problem clearly. I want a map that is able to:

map.put(new Key<String>(), new ArrayList<String>());
map.put(new Key<Integer>(), new ArrayList<Integer>());

以下代码不应编译:

map.put(new Key<String>(), new ArrayList<Integer>());

键值和值应始终具有相同的通用类型,通用类型可以是任意值,显然扩展地图不符合我的要求。

The key and value should always have the same generic type while the generic type can be any, and obviously extending a map does not meet my requirement.

推荐答案

我不知道任何现有的库正是这样,但它是不太难实现自己。过去我做了几次类似的事情。您不能使用标准的Map界面,但您可以使用内部的哈希映射来实现您的类。要开始,可能看起来像这样:

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

这篇关于如何声明具有变量泛型的地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆