Extending ArrayList and Creating new methods

可紊 提交于 2019-12-10 13:59:27

问题


I'm having a bit of a problem grasping something - I might be going about this completely wrong.

I am trying to create a class which extends ArrayList but has several methods which increase the functionality (at least for the program I am developing.)

One of the methods is a findById(int id), which searches each ArrayList object for a particular id match. So far it's working, but it won't let me do for (Item i : this) { i.getId(); }

I don't understand why?

Full code:

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

回答1:


Change

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

to

public class CustomArrayList extends ArrayList<Item> {

I suspect Item is the name of the class that you want to store in the list. By adding <Item> after CustomArrayList you're introducing a type parameter which shadows this class.


With the <Item> parameter, your code is equal to

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

which obviously won't always work, as T may refer to any type.




回答2:


What is getId()? Presumably it's a method in some class, but we don't know which class.

If you've actually got a class called Item with a getId() method, which this is meant to be a list of, you simply need to stop your class from being generic. So instead of this:

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

you want:

public class CustomArrayList extends ArrayList<Item> {

Currently within your class, Item doesn't refer to a class called Item, it refers to a type parameter called Item.

Now personally:

  • I wouldn't avoid creating singletons unless you really have to
  • If you have to, I'd avoid creating them in the way you have (which isn't thread-safe)
  • I wouldn't extend ArrayList<> unless I really had to, preferring composition over inheritance


来源:https://stackoverflow.com/questions/6524711/extending-arraylist-and-creating-new-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!