OOP:ArrayList al = new ArrayList() 和 List al = new ArrayList() 之间的区别?
Possible Duplicate:
List versus ArrayList
Difference between
ArrayList al = new ArrayList()
and
List al = new ArrayList() ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从创作的角度来看,没有。两者都创建一个 ArrayList 实例。
不同之处在于,在第二个示例中,
al
允许访问在List
接口上实现的所有方法,而在第一个示例中,al
允许访问 ArrayList 类的所有(可访问)方法和字段。实用的经验法则:使用第二种模式。如果您需要 ArrayList 实现中的一些额外功能,那么您可以随时强制转换:
None, from a creation perspective. Both create an instance of
ArrayList
.The difference is that, in you second example,
al
allows access to all methods implemented on theList
interface while, in the first example,al
allows access to all (accessible) methods and fields of theArrayList
class.A practical rule of thumb: use the second pattern. If you need some extra goodies from the
ArrayList
implementation, then you can always cast:这就是所谓的接口编程。假设您需要从您的方法返回此
列表
。因此调用代码可以将其放入List
变量中。现在,
对于后一种方法调用代码,可以将返回的列表存储在
List
类型变量中。出于某种原因,您稍后可以轻松决定,类似这样的事情:调用代码无需更改,而对于前者,您需要更改返回类型,这最终也会搞砸调用代码。
Its called programming to interface. Suppose, you need to return this
list
from your method. So the calling code can have that into aList
variable.And this,
Now for the latter method calling code can have the returned list in
List
type variable. And you can easily decide later, for some reason, something like this,No change in calling code, whereas with the former you need to change the return type, that would eventually screw up the calling code as well.
解释我对关于
Map
与HashMap
的这个非常相似的问题:没有区别物体之间。对象的界面有所不同。在第一种情况下,接口是
ArrayList
,而在第二种情况下,接口是List
。但底层对象是相同的。使用
List
的优点是,您可以将底层对象更改为不同类型的列表,而不会破坏与使用它的任何代码的约定。如果您将其声明为 ArrayList,则如果您想更改底层实现,则必须更改您的约定。Paraphrasing my answer to this very similar question about
Map
vs.HashMap
:There is no difference between the objects. There is a difference in the interface you have to the object. In the first case, the interface is
ArrayList
, whereas in the second it'sList
. The underlying object, though, is the same.The advantage to using
List
is that you can change the underlying object to be a different kind of list without breaking your contract with any code that's using it. If you declare it asArrayList
, you have to change your contract if you want to change the underlying implementation.