Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending ArrayList and Creating new methods

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);
    }
}
like image 660
Cody Avatar asked Jun 29 '11 17:06

Cody


2 Answers

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.

like image 155
aioobe Avatar answered Oct 10 '22 23:10

aioobe


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
like image 20
Jon Skeet Avatar answered Oct 10 '22 21:10

Jon Skeet