在 Java 1.5 中将非泛型列表类型转换为泛型列表类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1498963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting non-generic List type to Generic List type in Java 1.5
提问by Shaun F
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>.
我有一个保证只包含一个类型对象的列表。这是由我无法更新的库中的一些底层代码创建的。我想根据传入的 List 对象创建一个 List<ObjectType>,以便我的调用代码与 List<ObjectType> 对话。
What's the best way to convert the List (or any other object collection) to a List<ObjectType>.
将 List(或任何其他对象集合)转换为 List<ObjectType> 的最佳方法是什么。
采纳答案by erickson
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:
当与未指定泛型类型的类型参数的遗留代码进行互操作时,请使用通配符。例如,假设您正在调用旧库中的一个方法,该方法仅返回一个 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 cancast 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 ClassCastExceptionraised at runtime will occur right at an explicit cast.
在这种情况下,您有一个选择。您可以将结果强制转换为 a Collection<Item>,但如果这样做,您将 100% 依赖第三方库,并放弃 Java 泛型类型的保证:任何ClassCastException在运行时引发的都将在显式强制转换时发生。
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.
如果您不完全信任第三方库,但仍需要生成一个Collection<Item>? 然后创建一个新集合,并在将它们转换为预期类型后添加内容。这样,如果库中存在错误,您会立即发现它,而不是将一些代码放在很远的地方,然后在很久以后神秘地用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 factoriesof the Collectionsclass.
对于其中类型参数是不是在编译时已知的情况下,你可以使用类型检查收集工厂的的Collections类。
回答by daveb
You can simply cast the list:
您可以简单地投射列表:
List raw = new ArrayList();
List<String> generic = (List<String>) raw;
回答by nanda
The best and safest way is to use java.util.Collections method 'checkedList(List list, Class type)'
最好和最安全的方法是使用 java.util.Collections 方法 'checkedList(List list, Class type)'
With this method, all of the items in your old List will be checked as early as possible.
使用此方法,将尽早检查旧列表中的所有项目。
回答by sluimers
Try this:
试试这个:
List<ObjectType> objectsWithType = Arrays.asList((ObjectType[])wildcardObjects).toArray());
But remember that this will produce a fixed length List. If you try to add or remove element from this list, it will throw an error. So be always careful while using Arrays.asList().
但请记住,这将产生一个固定长度的 List。如果您尝试在此列表中添加或删除元素,则会引发错误。所以在使用时一定要小心Arrays.asList()。
回答by Trejkaz
If you just cast to List<T>in any old place you will get an "unchecked" compiler warning. We resolved that by moving it to a utility method.
如果您只是List<T>在任何旧位置强制转换,您将收到“未经检查”的编译器警告。我们通过将其移至实用方法来解决该问题。
public class Lists {
@SuppressWarnings({"unchecked"})
public static <T> List<T> cast(List<?> list) {
return (List<T>) list;
}
}
Caller now gets no warning, e.g.:
来电者现在不会收到警告,例如:
for (Element child : Lists.<Element>cast(parent.getChildren())) {
// ...
}
That checkedListutility is in theory a great idea, but in practice it sucks to have to pass in the class you expect. I hope Java will get runtime generic typing information eventually.
该checkedList实用程序在理论上是一个好主意,但在实践中,必须通过您期望的课程是很糟糕的。我希望 Java 最终会获得运行时通用类型信息。

