我应该声明/初始化的ArrayList的列表,的ArrayList,或者与LT的ArrayList;猫> [英] Should I declare/Initialize ArrayLists as Lists, ArrayLists, or ArrayLists of <Cat>

查看:127
本文介绍了我应该声明/初始化的ArrayList的列表,的ArrayList,或者与LT的ArrayList;猫>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么在声明集合作为这样的区别

 公共类CatHerder {
    私有列表猫;
    公共CatHerder(){
        this.cats =新的ArrayList< CAT和GT;();
    }
}
//要么
公共类CatHerder {
    私人ArrayList的猫;
    公共CatHerder(){
        this.cats =新的ArrayList();
    }
}
//要么
公共类CatHerder {
    私人的ArrayList< CAT和GT;猫;
    公共CatHerder(){
        this.cats =新的ArrayList< CAT和GT;();
    }
}


解决方案

您应该声明为列表<猫> ,并将其初始化为的ArrayList<猫方式>

列表 < /一>是一个接口,以及<一href=\"http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html\"><$c$c>ArrayList是一个实现类。它几乎总是preferable兑接口,而不是执行code。这样,如果你需要实施以后更改,也不会打破消费者谁code对接口。

根据您实际使用的名单,你甚至可以使用无特定的<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Collection.html\"><$c$c>java.util.Collection (其中列表扩展的接口)。

至于列表&LT;猫&GT; (你可以阅读,作为猫的名单)与列表:这是Java的 的仿制药,从而确保安全的编译时类型。总之,它可以让编译器确保了列表仅包含的对象。


 公共类CatHerder {
    私人最终名单&LT; CAT和GT;猫;
    公共CatHerder(){
        this.cats =新的ArrayList&LT; CAT和GT;();
    }
}

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

解决方案

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

这篇关于我应该声明/初始化的ArrayList的列表,的ArrayList,或者与LT的ArrayList;猫&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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