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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:12:11  来源:igfitidea点击:

cast List to ArrayList

javacollectionscasting

提问by Aladdin

When I want to cast the ArrayListobject in Listreference that returned from the method:

当我想ArrayListList从方法返回的引用中转换对象时:

public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}

The return type from the method asListis a Listreference to ArrayListobject, which means I can cast it to ArrayListreference. Such that :

方法的返回类型asListListArrayList对象的引用,这意味着我可以将其转换为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 ArrayListis concrete type that implement Listinterface. 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 Listwas used.

但是 API 应该以最抽象的方式公开。这就是为什么List使用了。