类型安全的涉及泛型的异构容器 [英] Typesafe heterogeneous containers involving generics

查看:88
本文介绍了类型安全的涉及泛型的异构容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个容器,为我提供一种存储通用类型元素的方式,例如

I need to create a container that provides a way for me to store elements of generic type, kind of like this effective java pattern but storing generic things

是否可以在涉及泛型类型的事物的情况下创建类型安全的异构容器?

Is it possible to create a typesafe heterogeneous container where generic typed things are involved?

<T> void put(T ele, SomeTypedThing<T> genEle);
<T> SomeTypedThing<T> get(T ele);

我可以将 Class< T> 添加为方法参数.示例:

I am fine to add the Class<T> as method param. example:

public static class Container {

    Map<Class<?>, Set<?>> store = new HashMap<>();

    public <T> void put(Set<T> ele, Class<T> type) {
        store.put(type, ele);
    }

    public <T> Set<T> get(Class<T> type) {
        return store.get(type);
    }
}

有可能实现这一目标吗?

would it be possible to achieve this?

Set<?> raw = store.get(type);
Set<T> typed = // some magic;

如何,或者为什么不呢?是Java不会做的事情还是基本的事情(因此,没有语言可以做,或者只是没有任何意义)

how, or why not? is it something that java doesn't do or is it something fundamental (so no language can do, or just doesn't make sense to do)

推荐答案

问题出在 Set 上的通配符参数上.与其使用 Set<?> 而不是使用 Set< Object> ,然后一切正常:

The problem is with the wildcard parameter on the Set. Instead of using a Set<?>, make it a Set<Object>, and everything works:

public static class Container {

    Map<Class<?>, Set<Object>> store = new HashMap<>();

    public <T> void put(T ele, Class<T> type) {
        store.putIfAbsent(type, new HashSet<>());
        store.get(type).add(ele);
    }

}

Set<?> Set< Object> 之间的区别是:

Set<?> 可以是任何类型的 Set -它可以是 Set< String> 设置<整数> .而且Java编译器希望确保您没有尝试将 String 对象添加到 Set< Integer> .

A Set<?> could be a Set of any type - it could be a Set<String> or a Set<Integer>. And the java compiler wants to make sure that you are not trying to add a String object to a Set<Integer>.

另一方面, Set< Object> 只是可以包含 Object 类实例的 Set .而且,由于 String Integer 都是 Object 的子类,因此您可以轻松地将字符串和Integer存储到这样的集合中.

On the other hand, a Set<Object> is just a Set that can contain instances of the Object class. And since String and Integer are both subclasses of Object, you can easily store strings and Integers into such a set.

添加方法

    public <T> Set<T> get(Class<T> type) {
        return (Set<T>) store.get(type);
    }

对该类的

会向编译器发出有关未经检查的强制转换的警告.在此可以安全地忽略此警告,因为您知道只向该 Set 添加了 T 类型的元素.

to the class gives a compiler warning about an unchecked cast. This warning can be safely ignored here, because you know that you added only elements of type T to that Set.

这篇关于类型安全的涉及泛型的异构容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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