簡體   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