茄子在线看片免费人成视频,午夜福利精品a在线观看,国产高清自产拍在线观看,久久综合久久狠狠综合

    <s id="ddbnn"></s>
  • <sub id="ddbnn"><ol id="ddbnn"></ol></sub>

  • <legend id="ddbnn"></legend><s id="ddbnn"></s>

    如何使用Java泛型映射不同的值類型
    來源:易賢網(wǎng) 閱讀:1298 次 日期:2015-04-10 14:04:52
    溫馨提示:易賢網(wǎng)小編為您整理了“如何使用Java泛型映射不同的值類型”,方便廣大網(wǎng)友查閱!

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

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

    關(guān)于這個主題,最近碰到一些不太合適的解決方案。它給了我在這篇文章中解釋這個問題域,并闡述一些實現(xiàn)細節(jié)的想法。

    使用Java泛型映射不同的值類型

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

    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 :

    Context context = new Context();

    Runnable runnable = ...

    context.put( "key", runnable );

    // several computation cycles later...

    Runnable value = ( Runnable )context.get( "key" );

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

    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

    產(chǎn)生這種問題的原因是很難被跟蹤到的,因為相關(guān)的實現(xiàn)步驟可能已經(jīng)廣泛分布在你的程序各個部分中。

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

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

    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 );

    }

    [...]

    }

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

    Context context = new Context();

    Runnable runnable = ...

    context.put( "key", runnable, Runnable.class );

    // several computation cycles later...

    Runnable value = context.get( "key", Runnable.class );

    乍一看,這段代碼可能會給你更類型安全的錯覺,因為其在第6行避免了向下轉(zhuǎn)型(down cast)。但是運行下面的代碼將使我們重返現(xiàn)實,因為我們?nèi)詫⒃诘?0行賦值語句處跌入ClassCastException 的懷抱:

    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中的向下轉(zhuǎn)型是無效的,因為類型擦除會使用靜態(tài)轉(zhuǎn)型的Object來代替無界參數(shù)(unbonded parameters)。此外更重要的是,這個實現(xiàn)根本就沒有用到由Context#put 提供的類型信息。這充其量是多此一舉的美容罷了。

    類型安全的異構(gòu)容器

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

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

    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 的實現(xiàn)中是如何用一個有效的動態(tài)變量替換向下轉(zhuǎn)型的??蛻舳丝梢赃@樣使用這個context:

    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 );

    這次客戶端的代碼將可以正常工作,不再有類轉(zhuǎn)換的問題,因為不可能通過一個不同的值類型來交換某個鍵值對。

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

    Bloch指出這種模式有兩個局限性。“首先,惡意的客戶端可以通過以原生態(tài)形式(raw form)使用class對象輕松地破壞類型安全?!睘榱舜_保在運行時類型安全可以在Context#put中使用動態(tài)轉(zhuǎn)換(dynamic cast)。

    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對象,所有的參數(shù)化類型指的是相同的List.class 對象。因此,Bloch指出對于這種局限性沒有滿意的解決方案。

    但是,假如你需要存儲兩個具有相同值類型的條目該怎么辦呢?如果僅為了存入類型安全的容器,可以考慮創(chuàng)建新的類型擴展,但這顯然不是最好的設(shè)計。使用定制的Key也許是更好的方案。

    多條同類型容器條目

    為了能夠存儲多條同類型容器條目,我們可以用自定義key改變Context 類。這種key必須提供我們類型安全所需的類型信息,以及區(qū)分不同的值對象(value objects)的標識。一個以String 實例為標識的、幼稚的key實現(xiàn)可能是這樣的:

    public class Key<T> {

    final String identifier;

    final Class<T> type;

    public Key( String identifier, Class<T> type ) {

    this.identifier = identifier;

    this.type = type;

    }

    }

    我們再次使用參數(shù)化的Class作為類型信息的鉤子,調(diào)整后的Context將使用參數(shù)化的Key而不是Class。

    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:

    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被用作查詢參數(shù)。用相同的identifier和class初始化兩個不同的Key的實例,一個用于put,另一個用于get,最后get操作將返回null 。這不是我們想要的……

    //譯者附代碼片段

    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設(shè)計合適的equals 和hashCode 可以輕松解決這個問題,進而使HashMap 查找按預(yù)期工作。最后,你可以為創(chuàng)建key提供一個工廠方法以簡化其創(chuàng)建過程(與static import一起使用時有用):

    public static Key key( String identifier, Class type ) {

    return new Key( identifier, type );

    }

    結(jié)論

    “集合API說明了泛型的一般用法,限制你每個容器只能有固定數(shù)目的類型參數(shù)。你可以通過將類型參數(shù)放在鍵上而不是容器上來避開這個限制。對于這種類型安全的 異構(gòu)容器,可以用Class對應(yīng)作為鍵?!保↗oshua Bloch,《Effective Java》第29項)。

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

    更多信息請查看IT技術(shù)專欄

    更多信息請查看網(wǎng)絡(luò)編程
    易賢網(wǎng)手機網(wǎng)站地址:如何使用Java泛型映射不同的值類型

    2026上岸·考公考編培訓(xùn)報班

    • 報班類型
    • 姓名
    • 手機號
    • 驗證碼
    關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
    工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
    聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
    咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)