具有两个相同类型元素的异构容器 [英] Heterogeneous Container with two element of same type
问题描述
我正在阅读有效Java - 项目29 。在这个例子中,它讨论了异构容器:
private Map< Class&对象> 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>我的问题是:如果有两个相同类型的元素需要,请问如何添加到 Map
,即两个 String
,这种模式是否仍然有用?解决方案如果你放两个字符串,第二个将覆盖第一个。因此,只有在需要此行为时才有用。如果要存储更多的对象在同一个键下,您可以使用其他容器,例如:
Map< Class& ;,List< Object>>
或者您可以使用Guava的MultiMap: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/ common / collect / Multimap.html
或者您可以使用apache commons中的MultiMap: http://commons.apache.org/proper/commons-collections/javadocs/ api-3.2.1 / org / apache / commons / collections / MultiMap.html
I am reading Effective Java - Item 29. It talks about Heterogeneous container, in the example:
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);
....
}
This pattern parametrises the key instead of values, so you are not limited to a single type, unlike:
private Map<Integer, String> favorites ....
My question is: what if there are two elements of same type that needed to be added to the Map
, i.e. two String
, is this pattern still useful?
解决方案 If you put two strings the second will override the first one. So it is useful only if this behaviour is desired. If you want to store more objects under the same key you can use other containers, for example :
Map<Class<?>, List<Object>>
Or you can use MultiMap from Guava : http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html
Or you can use MultiMap from apache commons : http://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/MultiMap.html
这篇关于具有两个相同类型元素的异构容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!