我应该将 ArrayLists 声明/初始化为 <Cat> 的 Lists、ArrayLists 或 ArrayLists 吗? [英] Should I declare/Initialize ArrayLists as Lists, ArrayLists, or ArrayLists of <Cat>
问题描述
声明一个集合有什么区别
What is the difference in declaring a collection as such
public class CatHerder{
private List cats;
public CatHerder(){
this.cats = new ArrayList<Cat>();
}
}
//or
public class CatHerder{
private ArrayList cats;
public CatHerder(){
this.cats = new ArrayList();
}
}
//or
public class CatHerder{
private ArrayList<Cat> cats;
public CatHerder(){
this.cats = new ArrayList<Cat>();
}
}
推荐答案
你应该把它声明为List
,并初始化为ArrayList
>.
You should declare it as a List<Cat>
, and initialize it as an ArrayList<Cat>
.
List
是一个接口,ArrayList
是一个实现类.几乎总是最好针对接口而不是实现进行编码.这样,如果您以后需要更改实现,就不会破坏针对接口编码的消费者.
List
is an interface, and ArrayList
is an implementing class. It's almost always preferable to code against the interface and not the implementation. This way, if you need to change the implementation later, it won't break consumers who code against the interface.
根据您实际使用列表的方式,您甚至可以使用不太具体的 java.util.Collection
(List
扩展的接口).
Depending on how you actually use the list, you might even be able to use the less-specific java.util.Collection
(an interface which List
extends).
至于List
(您可以将其读作猫列表")与List
:那是Java 的generics,确保编译时类型安全.简而言之,它让编译器确保 List
只包含 Cat
对象.
As for List<Cat>
(you can read that as "list of cat") vs List
: that's Java's generics, which ensure compile-time type safely. In short, it lets the compiler make sure that the List
only contains Cat
objects.
public class CatHerder{
private final List<Cat> cats;
public CatHerder(){
this.cats = new ArrayList<Cat>();
}
}
这篇关于我应该将 ArrayLists 声明/初始化为 <Cat> 的 Lists、ArrayLists 或 ArrayLists 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!