java 将 List 转换为 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16518804/
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
cast List to ArrayList
提问by Aladdin
When I want to cast the ArrayList
object in List
reference that returned from the method:
当我想ArrayList
在List
从方法返回的引用中转换对象时:
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
The return type from the method asList
is a List
reference to ArrayList
object, which means I can cast it to ArrayList
reference.
Such that :
方法的返回类型asList
是List
对ArrayList
对象的引用,这意味着我可以将其转换为ArrayList
引用。这样:
String[] colors = { "black", "blue", "yellow" };
ArrayList<String> links = (ArrayList<String>) Arrays.asList(colors) ;
But this code made run-time error :
但是这段代码产生了运行时错误:
Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
线程“main”中的异常 java.lang.ClassCastException:java.util.Arrays$ArrayList 无法转换为 java.util.ArrayList
Why it's happened?
为什么会发生?
回答by Damian Leszczyński - Vash
Your assumption that you can cast it to ArrayList is not valid.
您可以将其转换为 ArrayList 的假设是无效的。
The ArrayList
is concrete type that implement List
interface. It is not guaranteed that method asList
, will return this type of implementation.
该ArrayList
是实现的具体类型List
接口。不保证 methodasList
会返回这种类型的实现。
In fact the used type is java.util.Arrays$ArrayList
.
实际上使用的类型是java.util.Arrays$ArrayList
.
Using concrete class instead of interfaces. Can be recognized as bad practice. This approach is better when you have special type of class and you want to give a hint for future developer that this type is dedicated for the task.
使用具体类而不是接口。可以被认为是不好的做法。当您有特殊类型的类并且您想提示未来的开发人员该类型专用于该任务时,这种方法会更好。
But the API should exposed in the most abstract way. That is why the List
was used.
但是 API 应该以最抽象的方式公开。这就是为什么List
使用了。