繁体   English   中英

具有两个相同类型元素的异构容器

[英]Heterogeneous Container with two element of same type

我正在阅读有效Java条款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项实际上是关于使用参数化键的一般概念:

但是,有时您需要更大的灵活性。 例如,数据库行可以具有任意多的列,并且能够以类型安全的方式访问所有列将是一个很好的选择。 幸运的是,有一种简单的方法可以达到这种效果。 这个想法是参数化而不是容器

此项的目的是证明您可以通过多种方式使用泛型,而不仅仅是通过参数化类型。 异构容器模式只是此技术的一个示例。 诚然,该项目可以用更好的标题来使这一点更清楚,例如“ 考虑使用参数化方法在处理任意数量的类型时强制执行类型安全 ”。

该项目演示的“异构容器”模式专门用于要将某些类型与每种类型的特定实例相关联的情况。 GuavaClassToInstanceMap类型包括此模式的实现( 更多详细信息 )。 它们还提供了功能更强大的TypeToInstanceMap ,该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当前不包含这样的接口,但是ClassToInstanceMap实现非常简单,因此您可以轻松创建自己的ClassToInstanceMultimap实现。

如果您放置两个字符串,则第二个将覆盖第一个。 因此,仅在需要此行为时才有用。 如果要在同一键下存储更多对象,则可以使用其他容器,例如:

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

暂无
暂无

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

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