我不明白:
-
ArrayList<Integer> list = new ArrayList<Integer>();
-
Collection<Integer> list1 = new ArrayList<Integer>();
类 ArrayList
扩展实现接口(interface)的类 Collection
, 所以类 ArrayList
工具 Collection
界面。也许list1
允许我们使用 Collection
中的静态方法界面?
最佳答案
接口(interface)没有静态方法 [在 Java 7 中]。 list1
只允许访问 Collection
中的方法,而 list
允许访问 ArrayList
中的所有方法。
最好用尽可能不具体的类型来声明一个变量。因此,例如,如果出于任何原因将 ArrayList
更改为 LinkedList
或 HashSet
,则不必重构大部分代码(例如,客户端类)。
假设您有这样的东西(仅用于说明目的,不可编译):
class CustomerProvider {
public LinkedList<Customer> getAllCustomersInCity(City city) {
// retrieve and return all customers for that city
}
}
然后您决定实现它并返回一个 HashSet
。也许有一些客户端类依赖于您返回 LinkedList
并调用 HashSet
没有的方法(例如 LinkedList.getFirst()
)。
这就是为什么你最好这样做:
class CustomerProvider {
public Collection<Customer> getAllCustomersInCity(City city) {
// retrieve and return all customers for that city
}
}
关于java - ArrayList<Integer> list = new ArrayList<Integer>(); 之间的区别和 Collection<Integer> list1 = new ArrayList<Integer>();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14163291/