为什么arraylist 类实现List 并扩展AbstractList? [英] Why does arraylist class implement List as well as extend AbstractList?

查看:20
本文介绍了为什么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 类的 Arrays.asList() 方法包含它自己的 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);

我收到一个错误:cannot convert form List到 ArrayList
这背后的原因是什么?
编辑
Arrays.asList() 确实返回了它自己的 ArrayList 实现.检查 这个出来了.

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.

推荐答案

对于您的第一个问题,请查看 为什么 ArrayList 有implements List"?

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

回答你的第二个问题

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

正如你提到的 Arrays.asList 返回它的 自己的 AbstractList 实现,不幸的是,此代码的创建者也将此类命名为 ArrayList.现在因为我们不能水平转换但只有垂直返回的数组列表不能转换为 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆