java – 具有两个相同类型元素的异构容器
作者:互联网
我正在阅读Effective Java – Item 29.它讨论了异构容器,在这个例子中:
private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>();
public <T> void putFavirite(Class<T> type, T insance) {
if(type == null) {
throw new NullPointerException();
}
favorites.put(type, insance);
....
}
此模式参数化键而不是值,因此您不限于单一类型,不同于:
private Map<Integer, String> favorites ....
我的问题是:如果有两个相同类型的元素需要添加到Map中,即两个String,这个模式仍然有用吗?
解决方法:
首先,请注意第29项实际上是关于使用参数化键的一般概念:
Sometimes, however, you need more flexibility. For example, a database row can have arbitrarily many columns, and it would be nice to be able to access all of them in a typesafe manner. Luckily there is an easy way to achieve this effect. The idea is to parameterize the key instead of the container.
此项目的目的是证明您可以通过参数化类型的方式使用泛型.异构容器模式只是这种技术的一个例子.不可否认,该项目可以使用更好的标题更清晰,例如“在使用任意数量的类型时,考虑使用参数化方法来强制执行类型安全”.
该项演示的异构容器模式专门用于您希望将某些类型与每种类型的特定实例相关联的情况. Guava包括07.02类型(more details)的此模式的实现.它们还提供了功能更强大的TypeToInstanceMap
,它支持任意泛型类型(例如List< String>),其中包含一些稍微麻烦的API.
所有这一切都是说,没有什么能阻止你创建一个支持给定类型的多个实例的类似结构的类.我们可以轻松地使用ClassToInstanceMap API并创建ClassToInstanceMultimap类型(扩展Guava的Multimap
API):
public interface ClassToInstanceMultimap<B> extends Multimap<Class<? extends B>, B> {
/**
* Returns the values the specified class is mapped to, or an empty collection if no
* entries for this class is present. This will only return a value that was
* bound to this specific class, not a value that may have been bound to a
* subtype.
*/
<T extends B> Collection<T> getInstances(Class<T> type);
/**
* Stores an entry mapping the specified class to the specified value. Does <i>not</i>
* associate this value with any of the class's supertypes.
*
* @return {@code true} if the method increased the size of the multimap, or
* {@code false} if the multimap already contained the key-value pair and doesn't allow
* duplicates
*/
<T extends B> T putInstance(Class<T> type, T value);
}
Guava目前不包含这样的接口,但implementation of ClassToInstanceMap
非常简单,因此您可以轻松创建自己的ClassToInstanceMultimap实现.
标签:effective-java,java,map 来源: https://codeday.me/bug/20191003/1845807.html