嵌套的java集合泛型
我想调用一个像这样定义的方法
<T> void foo(Class<? extends Collection<T>>)
,但是编译器无法让我通过
foo(ArrayList<Integer>.class);
获取泛型类型的类型类的语法是什么?
我正在实现常见的情况,我有一个
Map<Key, Collection<Value>>
并且想要在集合中插入一个值。如果该集合不存在,则应创建一个新集合并将值插入其中。 到目前为止,我有以下代码,但带有类型安全警告:
public static <K, V, C extends Collection<V>> boolean addToMappedCollectionNotNull(Map<K, C> aMap, K key, V element, Class<? extends Collection> type) {
C collection = aMap.get(key);
if (collection == null) {
try {
collection = (C)type.newInstance();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
aMap.put(key, collection);
}
return collection.add(element);
}
I'd like to call a method defined like
<T> void foo(Class<? extends Collection<T>>)
but there is no way the compiler let me pass
foo(ArrayList<Integer>.class);
What is the syntax to get the type class of a generic type?
I am implementing the common case where I have a
Map<Key, Collection<Value>>
and want to insert a value in the collection. If the collection does not exist it should create a new one and insert the value in it.
So far I have the following code, but with type safety warnings:
public static <K, V, C extends Collection<V>> boolean addToMappedCollectionNotNull(Map<K, C> aMap, K key, V element, Class<? extends Collection> type) {
C collection = aMap.get(key);
if (collection == null) {
try {
collection = (C)type.newInstance();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
aMap.put(key, collection);
}
return collection.add(element);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Boris 所说,您可能正在寻找 MultiMap。但是,如果您认为必须传输类型信息 超级类型令牌 是一个解决方案。 Guice 有一个 TypeLiteral 实现您可以查看。
As Boris said you're probably looking for a MultiMap. But if you think that you have to transport the type information the super type token is a solution. Guice has a TypeLiteral implementation you can look at.
使用 Google 的 Guava 库也可以实现相同的目标。有一个接口
Multimap< ;K, V>
将值集合V
与键K
相关联。Multimap
由ListMultimap
、SetMultimap
和SortedSetMultimap
实现,涵盖值集合的所有可能需求V。
Same goal can be achieved using Google's Guava library. There's an interface
Multimap<K, V>
which associates a collection of valuesV
to a keyK
.Multimap
is implemented by aListMultimap
,SetMultimap
andSortedSetMultimap
covering all possible needs for the collection of valuesV
.您无法获取参数化类型的
class
,因为存在 没有确切的运行时类型表示。您将不得不重新设计它,以免将如此多的逻辑放在一个地方。也许可以将测试
null
Collection
的部分与在不同位置(例如工厂)创建集合的部分分开。You cannot get the
class
of a parameterized type because there is no exact runtime type representation.You will have to re-design this to not put so much logic in one place. Maybe separate the part out that tests for a
null
Collection
and the part the creates one in a different place, like a Factory.