如何声明一个ArrayList? [英] How to declare an ArrayList?

查看:50
本文介绍了如何声明一个ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么应该首选Java类的接口?

我对java还是比较陌生的,我才刚刚开始使用collections框架.在 ArrayList 上,我遇到了两种人们声明它的方式.例如,声明一个 String s的 ArrayList :

I m relatively new to java and i have just started on collections framework. While on ArrayList I encountered on two ways people declare it. For example to declare an ArrayList of Strings :

List<String> l = new ArrayList<String>();

ArrayList<String> al = new ArrayList<String>();

我应该使用这两个中的哪一个,它们之间有什么区别?

Which one of these two should I use and what is the difference between them?

我知道实际调用的方法是在运行时确定的,因此,被调用的方法将仅属于 ArrayList 类,但是仍然第一个声明限制了可以调用的方法.

I know that the actual methods called are decided at runtime and hence the methods called will all be of ArrayList class only but still the first declaration restricts the methods that can be called.

我听说,第一种方法称为编码到接口".任何方法都将使用变量 l 调用,因此只能调用 List 接口提供的方法,而在第二个示例中,我们可以调用不仅提供的所有方法按 List ,但也按 Object 类(如 finalize() wait()等).那么,为什么人们甚至首先使用第一个声明呢?

The first way is, I have heard, called "coding to an interface". Any method will be invoked using the variable l and hence only methods provided by List interface can be called, whereas, in the second example we can call all the methods provided not only by List but by the Object class also (like finalize(), wait() etc). So why even in the first place people even use the first declaration??

推荐答案

您应始终使用尽可能少的特定接口.如果存在更合适的替代实现,则可以更轻松地替代替代实现.例如,采用 List 的方法不在乎列表是链接列表还是数组列表.您可以选择更合适的一个.

You should always use least specific interface possible. This makes it easier to substitute alternate implementations if a more appropriate one exists. For example, methods that take List don't care if the list is a linked list or an array list. You can choose whichever one is more appropriate.

这篇关于如何声明一个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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