在Java 1.5中将非通用列表类型转换为通用列表类型 [英] Converting non-generic List type to Generic List type in Java 1.5
问题描述
我有一个列表,保证只包含一个类型对象。这是由库中的一些基础代码创建的,我无法更新。我想创建一个List< ObjectType>基于传入的List对象,使我的调用代码与List< ObjectType>通信。
将List(或任何其他对象集合)转换为
当与没有为通用类型指定类型参数的传统代码进行互操作时,使用一个列表
通配符。例如,假设您在较旧的库中调用一个方法,该库只返回一个原始 Collection
:
Collection getItems();
在您的代码中,将结果分配给用通配符声明的变量:
集合<?> items = widget.getItems();
这样,您就可以保留类型安全,这样您就不会收到任何警告。
遗留代码可能指定(在注释中,很可能)通用参数应该是什么。例如:
/ **
* @返回项目,作为{@link Item}实例集合。
* /
Collection getItems();
在这种情况下,您可以选择。您可以将结果投射到集合< Item>
,但如果这样做,您将完全依赖第三方库,并放弃Java通用类型的保证:在运行时引发的任何 ClassCastException
将在显式转换时发生。
如果您不完全信任第三方库,但仍需要产生 Collection< Item>
,该怎么办?然后创建一个新集合,并在将它们转换为预期类型后添加内容。这样,如果库中有一个错误,你马上找到它,而不是有一些代码远远,后来神秘地炸了一个 ClassCastException
。
例如:
集合<?& tmp = widget.getItems();
Collection< Item> items = new ArrayList< Item>(tmp.size());
for(Object o:tmp)
items.add((Item)o); / *任何类型的错误都会在这里发现! * /
对于编译时未知类型参数的情况, 类型检查的收集工厂 收藏
类。
I have a List that is guaranteed to contain just one type object. This is created by some underlying code in a library that I cannot update. I want to create a List<ObjectType> based on the incoming List object so that my calling code is talking to List<ObjectType>.
What's the best way to convert the List (or any other object collection) to a List<ObjectType>.
When inter-operating with legacy code that doesn't specify type parameters for generic types, use a wildcard. For example, suppose you are calling a method in an older library that simply returns a raw Collection
:
Collection getItems();
In your code, assign the result to a variable declared with a wildcard:
Collection<?> items = widget.getItems();
This way, you preserve type safety so you won't get any warnings.
The legacy code might specify (in a comment, most likely) what the generic parameters should be. For example:
/**
* @return the items, as a Collection of {@link Item} instances.
*/
Collection getItems();
In this case, you have a choice. You can cast the result to a Collection<Item>
, but if you do so, you are relying 100% on the third-party library, and discarding the assurance of Java generic types: that any ClassCastException
raised at runtime will occur right at an explicit cast.
What if you don't fully trust the third-party library, but still need to produce a Collection<Item>
? Then create a new collection, and add the contents after casting them to the expected type. That way, if there is a bug in the library, you find out about it right away, rather than having some code far away and much later mysteriously blow up with a ClassCastException
.
For example:
Collection<?> tmp = widget.getItems();
Collection<Item> items = new ArrayList<Item>(tmp.size());
for (Object o : tmp)
items.add((Item) o); /* Any type error will be discovered here! */
For a case where the type parameter isn't known at compile-time, you can use the type-checked collection factories of the Collections
class.
这篇关于在Java 1.5中将非通用列表类型转换为通用列表类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!