(转载)Java Map中的Value值如何做到可以为任意类型的值 | 您所在的位置:网站首页 › map可以存list吗 › (转载)Java Map中的Value值如何做到可以为任意类型的值 |
转载地址: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)的实现可能是这样的: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Context { private final Map values = new HashMap(); public void put( String key, Object value ) { values.put( key, value ); } public Object get( String key ) { return values.get( key ); } [...] }接下来的代码片段展示了怎样在程序中使用Context : 1 2 3 4 5 6 Context context = new Context(); Runnable runnable = ... context.put( "key", runnable ); // several computation cycles later... Runnable value = ( Runnable )context.get( "key" );可以看出,这种方法的缺点是在第6行需要进行向下转型(down cast)。如果替换键值对中值的类型,显然会抛出一个ClassCastException异常: 1 2 3 4 5 6 7 8 9 10 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的变种: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Context { private final values = new HashMap(); public void put( String key, T value, Class valueType ) { values.put( key, value ); } public T get( String key, Class valueType ) { return ( T )values.get( key ); } [...] }同样的基本用法可能是这样的: 1 2 3 4 5 6 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 的怀抱: 1 2 3 4 5 6 7 8 9 10 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)。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Context { private final Map, Object> values = new HashMap(); public void put( Key key, T value ) { values.put( key, value ); } public T get( Key key ) { return key.type.cast( values.get( key ) ); } [...] }客户端将这样使用这个版本的Context: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Context context = new Context(); Runnable runnable1 = ... Key key1 = new Key( "id1", Runnable.class ); context.put( key1, runnable1 ); Runnable runnable2 = ... Key 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 。这不是我们想要的…… 1 2 3 4 5 6 7 8 9 //译者附代码片段 Context context = new Context(); Runnable runnable1 = ... Key key1 = new Key( "same-id", Runnable.class ); Key key2 = new Key( "same-id", Runnable.class ); context.put( key1, runnable1 );//一个用于put context.get(key2); //另一个用于get --> return null;幸运的是,为Key设计合适的equals 和hashCode 可以轻松解决这个问题,进而使HashMap 查找按预期工作。最后,你可以为创建key提供一个工厂方法以简化其创建过程(与static import一起使用时有用): 1 2 3 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[ 转载请保留原文出处、译者和译文链接。] |
CopyRight 2018-2019 实验室设备网 版权所有 |