为了账号安全,请及时绑定邮箱和手机立即绑定

关于Hadoop的问题,以下语法有什么区别?

关于Hadoop的问题,以下语法有什么区别?

红颜莎娜 2021-05-17 18:14:42
list = Lists.newArrayList();和正常的list=new ArrayList(); 有什么区别?
查看完整描述

3 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

List是一个接口,而ArrayList 是一个类。

1、ArrayList 继承并实现了List。List list = new ArrayList();这句创建了一个ArrayList的对象后把上溯到了List。此时它是一个List对象了,有些ArrayList有但是List没有的属性和方法,它就不能再用了。而ArrayList list=new ArrayList;创建一对象则保留了ArrayList的所有属性。

2、为什么一般都使用 List list = new ArrayList ,而不用 ArrayList alist = new ArrayList呢。问题就在于List有多个实现类,如 LinkedList或者Vector等等,现在你用的是ArrayList,也许哪一天你需要换成其它的实现类呢。

3、这时你只要改变这一行就行了:List list = new LinkedList; 其它使用了list地方的代码根本不需要改动。假设你开始用 ArrayList alist = new ArrayList,这下你有的改了,特别是如果你使用了 ArrayList特有的方法和属性。 ,如果没有特别需求的话,最好使用List list = new LinkedList,便于程序代码的重构,这就是面向接口编程的好处。

4、ava的多态,List只是定义了一堆接口,而对于这些接口,有各种各样的实现,比如ArrayList,LinkedList等等,不同的实现,会有自己不同的特性以及追加自己特有的方法。当你仅仅使用List的通用接口方法时,定义成List(也就是面向接口编程)是非常好的习惯。


查看完整回答
反对 回复 2021-05-23
?
守候你守候我

TA贡献1802条经验 获得超10个赞

这个方法在google工具类中也有,源码内容如下

123public static <E> ArrayList<E> newArrayList() {    return new ArrayList();}

内容是差不多的,唯一的好处就是可以少写泛型的部分。

这个方法有着丰富的重载:

123Lists.newArrayList(E... elements)Lists.newArrayList(Iterable<? extends E> elements)Lists.newArrayList(Iterator<? extends E> elements)

还有很多前缀扩展方法:

12List<T> exactly = Lists.newArrayListWithCapacity(100);List<T> approx = Lists.newArrayListWithExpectedSize(100);

使得函数名变得更有可读性,一眼就看出方法的作用。

但是查看源码发现官方的注解里头是这么写的:

Creates a mutable, empty ArrayList instance (for Java 6 and earlier).
创建一个可变的空ArrayList(适用于java 6及之前的版本)

Note for Java 7 and later: this method is now unnecessary and should
be treated as deprecated. Instead, use the ArrayList constructor
directly, taking advantage of the new "diamond" syntax.

针对java 7及之后版本,本方法已不再有必要,应视之为过时的方法。取而代之你可以直接使用ArrayList的构造器,充分利用钻石运算符<>(可自动推断类型)。



查看完整回答
反对 回复 2021-05-23
  • 3 回答
  • 0 关注
  • 707 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信