本文介绍了为什么arraylist类实现List以及扩展AbstractList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.ArrayList 的实现实现 List 以及扩展 AbstractList 。但是在java文档中你可以看到AbstractList已经实现了List。那么实现List以及扩展AbstractList不是多余的吗?


我的第二个问题



请查看以下代码:

The implementation of java.util.ArrayList implements List as well as extends AbstractList. But in java docs you can see that AbstractList already implements List. Then wouldn't it be redundant to implement List as well as extend AbstractList?
My second question

Please have a look at the following code :

String str = "1,2,3,4,5,6,7,8,9,10";
String[] stra = str.split(",");
List<String> a = Arrays.asList(stra);

Arrays.asList()方法Arrays类包含自己的ArrayList实现。但是这个只扩展了AbstractList,但没有实现List。但上面的代码编译。

但是当代码被修改为以下代码时

The Arrays.asList() method of the Arrays class contains its own implementation of ArrayList. But this one only extends AbstractList but does not implement List. But the above code compiles.
BUT when the code is modified to the following

String str = "1,2,3,4,5,6,7,8,9,10";
String[] stra = str.split(",");
java.util.ArrayList<String> a = Arrays.asList(stra);

我收到错误:无法转换表单List< String>到ArrayList< String>


这背后的原因是什么?


编辑

Arrays.asList()确实返回自己的实现数组列表。检查。

I get an error : cannot convert form List<String> to ArrayList<String>
What is the reason behind this?
EDIT
Arrays.asList() does return its own implementation of ArrayList. Check this out.

推荐答案

关于第一个问题,请看一下

For your first question take a look at Why does ArrayList have "implements List"?

回答你的第二个问题

java.util.ArrayList<String> a = Arrays.asList(stra);

如你所提到的 Arrays.asList 返回 java.utli.ArrayList 但只能转换为 java.util.AbstractList 或其超类型如 java.util.List 这就是你的第一个代码示例有效的原因。

as you mentioned Arrays.asList returns its own implementation of AbstractList and unfortunately creators of this code also named this class ArrayList. Now because we cant cast horizontally but only vertically returned array list can't be cast to java.utli.ArrayList but only to java.util.AbstractList or its super types like java.util.List that is why your first code example works.

这篇关于为什么arraylist类实现List以及扩展AbstractList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!