You should declare it as a List<Cat>
, and initialize it as an ArrayList<Cat>
.
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.
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).
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>();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…