声明List< Integer> vs ArrayList< Integer&gt ;? [英] What is the difference between declaring List<Integer> vs ArrayList<Integer>?

查看:216
本文介绍了声明List< Integer> vs ArrayList< Integer&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<Integer> mylist = new ArrayList<Integer>();

ArrayList<Integer> mylist2 = new ArrayList<Integer>();

我想知道上面两个在java集合API之间的实际区别是什么。我是新的java集合API。我知道List是ArrayList类实现的接口。

I am wondering what is the actual difference between the above two in java collections API. I am new to java collections API. I know that List is an interface that ArrayList class implements.

推荐答案

在您的声明1中,由于您将 mylist code> List< Integer> ,而它仍然是 ArrayList< Integer> ,因此您可以使用仅列出接口。如果您使用cross class.method功能,这是更好的语句。

In your statement 1, since you are referring mylist as List<Integer> while it is still ArrayList<Integer>, hence you can use the methods available in the List interface ONLY. This is better statement, if you are using cross class.method functionality.

接受 List< Integer> 的任何方法都可以接受 List 的任何实现类 LinkedList< Integer> 或您的自定义实现类。

Also any method accepting List<Integer> can accept any of the implementation classes of List e.g. LinkedList<Integer> or your custom implementation class.

您的第二个语句创建并引用 ArrayList< Integer> 有些人在 mylist 在本方法中使用时会忽略。

Your second statement, creates and references the object as ArrayList<Integer> ONLY. Some people perefer it when mylist is to be used locally in the method.

这篇关于声明List&lt; Integer&gt; vs ArrayList&lt; Integer&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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