Search code examples
javalistcollectionsextending

How to extend a list in java to store additional metadata and force it to accept only one type of objects?


In addition to the included items, I have to store the name and the id of the List inside itself. Thus i extended an ArrayList as follows:

class MyList<E> extends ArrayList<E>{
    private int id;
    private String name;

    MyList(int id, String name){
        this.id = id;
        this.name = name;
    }
    id getId(){       return id;   }
    String getName(){ return name; }
}

Now I realized, that this extension will only hold one specific type of objects. So how can I remove the generic character of my list?

class MyList<MyObject> extends ArrayList<E>
class MyList<MyObject> extends ArrayList<MyObject>

...and so on fails. I want to instantiate my list by

MyList mylist = new MyList();

...and it should automatically accept only MyObjects...

(Would it be better to create a wrapper which holds an ArrayList in addition to the meta? But because it is still a list, why remove all list-typical capabilities...)


Solution

  • You'll need

    class MyList extends ArrayList<MyObject>
    

    When you declare a type parameter for your class declaration like so

    class MyList<MyObject> ...
    

    the type MyObject> is not your type, it is a type variable that also has the name MyObject.

    What you want, is to use your MyObject type as a type argument for the ArrayList type parameter as shown above.


    But, as others have suggested, composition is probably a better way to do this, ie the wrapper you suggested in your question.