Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

java - 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>();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...