简体   繁体   English

Java泛型映射键值键入

[英]Java Generics Map Key-Value Typing

I'm wanting a method to return something like 我想要一种方法来返回类似

Map<Class<T>, List<T>>

where the map's keys correspond to lists of instances of that class, but the map can contain many different types of classes. 映射的键对应于该类的实例列表,但是映射可以包含许多不同类型的类。 Is there a way to enforce that the typing of the key and value must correspond, while allowing all different types to be stored in the map? 有没有一种方法可以强制键和值的键入必须相对应,同时允许所有不同类型存储在映射中?

public class ClassInstancesMap {

    private Map<Class<?>, List<?>> map;

    public ClassInstancesMap() {
        map = new HashMap<>();
    }

    public <T> void put(Class<T> key, List<T> list) {
        for (T e : list)
            if (key != e.getClass())
                throw new IllegalArgumentException(
                    "Type not match key=" + key
                    + " element=" + e
                    + "(class=" + e.getClass() + ")");
        map.put(key, list);
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> get(Class<T> key) {
        return (List<T>)map.get(key);
    }

    @Override
    public String toString() {
        return map.toString();
    }
}

The following example is compilable, but it throws runtime exception. 以下示例是可编译的,但是会引发运行时异常。 So this map enforce that the typing of the key and value must correspond 因此,此映射强制键和值的键入必须对应

ClassInstanesMap map = new ClassInstancesMap();
map.put(Object.class, Arrays.asList(1, 2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM