Java Map中的Value值如何做到可以為任意類型的值,mapvalue

來源:互聯網
上載者:User

(轉載)Java Map中的Value值如何做到可以為任意類型的值,mapvalue

轉載地址:http://www.importnew.com/15556.html     如有侵權,請聯絡作者及時刪除.

搬到我的部落格來,有空細細品味,把玩.

 

本文由 ImportNew - shutear 翻譯自 javacodegeeks。歡迎加入翻譯小組。轉載請見文末要求。

一般來說,開發人員偶爾會遇到這樣的情形: 在一個特定容器中映射任意類型的值。然而Java 集合API只提供了參數化的容器。這限制了型別安全地使用HashMap,如單一的實值型別。但如果想混合蘋果和梨,該怎樣做呢?

幸運的是,有一個簡單的設計模式允許使用Java泛型映射不同的實值型別,Joshua Bloch在其《Effective Java》(第二版,第29項)中將其描述為型別安全的異構容器(typesafe hetereogeneous container)。

關於這個主題,最近碰到一些不太合適的解決方案。它給了我在這篇文章中解釋這個問題域,並闡述一些實現細節的想法。

使用Java泛型映射不同的實值型別

考慮一個例子,你需要提供某種應用程式的上下文,它可以將特定的鍵綁定到任意類型的值。利用String作為鍵的HashMap,一個簡單的、非型別安全(type safe)的實現可能是這樣的:

1234567891011121314 public class Context {   private final Map<String,Object> values = new HashMap<>();   public void put( String key, Object value ) {    values.put( key, value );  }   public Object get( String key ) {    return values.get( key );  }   [...]}

接下來的程式碼片段展示了怎樣在程式中使用Context :

123456 Context context = new Context();Runnable runnable = ...context.put( "key", runnable ); // several computation cycles later...Runnable value = ( Runnable )context.get( "key" );

可以看出,這種方法的缺點是在第6行需要進行向下轉型(down cast)。如果替換索引值對中值的類型,顯然會拋出一個ClassCastException異常:

12345678910 Context context = new Context();Runnable runnable = ...context.put( "key", runnable ); // several computation cycles later...Executor executor = ...context.put( "key", executor ); // even more computation cycles later...Runnable value = ( Runnable )context.get( "key" ); // runtime problem

產生這種問題的原因是很難被跟蹤到的,因為相關的實現步驟可能已經廣泛分布在你的程式各個部分中。

為了改善這種情況,貌似將value和它的key、它的value都進行綁定是合理的。

在我看到的、按照這種方法的多種解決方案中,常見的錯誤或多或少歸結於下面Context的變種:

1234567891011121314 public class Context {   private final <String, Object> values = new HashMap<>();   public <T> void put( String key, T value, Class<T> valueType ) {    values.put( key, value );  }   public <T> T get( String key, Class<T> valueType ) {    return ( T )values.get( key );  }   [...]}

同樣的基本用法可能是這樣的:

123456 Context context = new Context();Runnable runnable = ...context.put( "key", runnable, Runnable.class ); // several computation cycles later...Runnable value = context.get( "key", Runnable.class );

乍一看,這段代碼可能會給你更型別安全的錯覺,因為其在第6行避免了向下轉型(down cast)。但是運行下面的代碼將使我們重返現實,因為我們仍將在第10行指派陳述式處跌入ClassCastException 的懷抱:

12345678910 Context context = new Context();Runnable runnable = ...context.put( "key", runnable, Runnable.class ); // several computation cycles later...Executor executor = ...context.put( "key", executor, Executor.class ); // even more computation cycles later...Runnable value = context.get( "key", Runnable.class ); // runtime problem

哪裡出問題了呢?

首先,Context#get中的向下轉型是無效的,因為類型擦除會使用靜態轉型的Object來代替無界參數(unbonded parameters)。此外更重要的是,這個實現根本就沒有用到由Context#put 提供的類型資訊。這充其量是多此一舉的美容罷了。

型別安全的異構容器

雖然上面Context 的變種不起作用,但卻指明了方向。接下來的問題是:怎樣合理地參數化這個key? 為了回答這個問題,讓我們先看看一個根據Bloch所描述的型別安全異構容器模式(typesafe heterogenous container pattern)的簡裝實現吧。

我們的想法是用key自身的class 類型作為key。因為Class 是參數化類別型,它可以確保我們使Context方法是型別安全的,而無需訴諸於一個未經檢查的強制轉換為T。這種形式的一個Class 對象稱之為類型令牌(type token)。

1234567891011121314 public class Context {   private final Map<Class<?>, Object> values = new HashMap<>();   public <T> void put( Class<T> key, T value ) {    values.put( key, value );  }   public <T> T get( Class<T> key ) {    return key.cast( values.get( key ) );  }   [...]}

請注意在Context#get 的實現中是如何用一個有效動態變數替換向下轉型的。用戶端可以這樣使用這個context:

12345678910 Context context = new Context();Runnable runnable ...context.put( Runnable.class, runnable ); // several computation cycles later...    Executor executor = ...context.put( Executor.class, executor ); // even more computation cycles later...Runnable value = context.get( Runnable.class );

這次用戶端的代碼將可以正常工作,不再有類轉換的問題,因為不可能通過一個不同的實值型別來交換某個索引值對。

有光明的地方就必然有陰影,有陰影的地方就必然有光明。不存在沒有陰影的光明,也不存在沒有光明的陰影。村上春樹

Bloch指出這種模式有兩個局限性。“首先,惡意的用戶端可以通過以原生態形式(raw form)使用class對象輕鬆地破壞型別安全。”為了確保在運行時型別安全可以在Context#put中使用動態轉換(dynamic cast)。

123 public <T> void put( Class<T> key, T value ) {  values.put( key, key.cast( value ) );}

第二個局限在於它不能用在不可具體化(non-reifiable )的類型中(見《Effective Java》第25項)。換句話說,你可以儲存Runnable 或Runnable[],但是不能儲存List<Runnable>

這是因為List<Runnable>沒有特定class對象,所有的參數化型別指的是相同的List.class 對象。因此,Bloch指出對於這種局限性沒有滿意的解決方案。

但是,假如你需要儲存兩個具有相同實值型別的條目該怎麼辦呢?如果僅為了存入型別安全的容器,可以考慮建立新的類型擴充,但這顯然不是最好的設計。使用定製的Key也許是更好的方案。

多條同類型容器條目

為了能夠儲存多條同類型容器條目,我們可以用自訂key改變Context 類。這種key必須提供我們型別安全所需的類型資訊,以及區分不同的值對象(value objects)的標識。一個以String 執行個體為標識的、幼稚的key實現可能是這樣的:

12345678910 public class Key<T> {   final String identifier;  final Class<T> type;   public Key( String identifier, Class<T> type ) {    this.identifier = identifier;    this.type = type;  }}

我們再次使用參數化的Class作為類型資訊的鉤子,調整後的Context將使用參數化的Key而不是Class

1234567891011121314 public class Context {   private final Map<Key<?>, Object> values = new HashMap<>();   public <T> void put( Key<T> key, T value ) {    values.put( key, value );  }   public <T> T get( Key<T> key ) {    return key.type.cast( values.get( key ) );  }   [...]}

用戶端將這樣使用這個版本的Context

1234567891011121314 Context context = new Context(); Runnable runnable1 = ...Key<Runnable> key1 = new Key<>( "id1", Runnable.class );context.put( key1, runnable1 ); Runnable runnable2 = ...Key<Runnable> key2 = new Key<>( "id2", Runnable.class );context.put( key2, runnable2 ); // several computation cycles later...Runnable actual = context.get( key1 ); assertThat( actual ).isSameAs( runnable1 );

雖然這個程式碼片段可用,但仍有缺陷。在Context#get中,Key被用作查詢參數。用相同的identifier和class初始化兩個不同的Key的執行個體,一個用於put,另一個用於get,最後get操作將返回null 。這不是我們想要的……

123456789 //譯者附程式碼片段Context context = new Context(); Runnable runnable1 = ...Key<Runnable> key1 = new Key<>( "same-id", Runnable.class );Key<Runnable> key2 = new Key<>( "same-id", Runnable.class );context.put( key1, runnable1 );//一個用於put context.get(key2); //另一個用於get --> return null;

幸運的是,為Key設計合適的equals 和hashCode 可以輕鬆解決這個問題,進而使HashMap 尋找按預期工作。最後,你可以為建立key提供一個Factory 方法以簡化其建立過程(與static import一起使用時有用):

123 public static  Key key( String identifier, Class type ) {  return new Key( identifier, type );}
結論

“集合API說明了泛型的一般用法,限制你每個容器只能有固定數目的型別參數。你可以通過將型別參數放在鍵上而不是容器上來避開這個限制。對於這種型別安全的 異構容器,可以用Class對應作為鍵。”(Joshua Bloch,《Effective Java》第29項)。

給出上述閉幕詞,也沒有什麼要補充的了,除了祝願你成功混合蘋果和梨……

原文連結: javacodegeeks 翻譯: ImportNew.com - shutear
譯文連結: http://www.importnew.com/15556.html
[ 轉載請保留原文出處、譯者和譯文連結。]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.