扩展ArrayList并创建新方法

Cod*_*ody 5 java arraylist extend

我抓住了一些问题 - 我可能会对此完全错误.

我正在尝试创建一个扩展ArrayList的类,但有几个方法可以增加功能(至少对于我正在开发的程序而言).

其中一个方法是findById(int id),它在每个ArrayList对象中搜索特定的id匹配.到目前为止,它正在发挥作用,但它不会让我这样做for (Item i : this) { i.getId(); }

我不明白为什么?

完整代码:

public class CustomArrayList<Item> extends ArrayList<Item> {

    // declare singleton instance
    protected static CustomArrayList instance;

    // private constructor
    private CustomArrayList(){
        // do nothing
    }

    // get instance of class - singleton
    public static CustomArrayList getInstance(){
        if (instance == null){
            instance = new CustomArrayList();
        }
        return instance;
    }

    public Item findById(int id){
        Item item = null;
        for (Item i : this) {
            if (i.getId() == id) {
                      // something
         }
        }
        return item;
    }
    public void printList(){
        String print = "";
        for (Item i : this) {
            print += i.toString() + "\n";
        }
        System.out.println(print);
    }
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 7

更改

public class CustomArrayList<Item> extends ArrayList<Item> {
Run Code Online (Sandbox Code Playgroud)

public class CustomArrayList extends ArrayList<Item> {
Run Code Online (Sandbox Code Playgroud)

我怀疑Item是您要在列表中存储的类的名称.通过在引入影响此类的类型参数<Item>后添加.CustomArrayList


使用<Item>参数,您的代码等于

public class CustomArrayList<T> extends ArrayList<T> {
    // ...
        for (T i : this) { i.getId(); }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这显然不会一直有效,T可以指任何类型.