views:

412

answers:

3

I've been trying to extend the ArrayList class without much success. I want to extend it, and be able to parameterize it.

So normally you have something like

ArrayList<SomeObject> list = new ArrayList<SomeObject>();

I want

MyList<SomeObject> list = new MyList<SomeObject>();

Simply extending ArrayList doesn't work.

public class MyList extends ArrayList ...

The when I try to use it I get the error

The type MyList is not generic; it cannot be parameterized with arguments <SomeObject>

I've tried variations of

public class MyList extends ArrayList<Object>
public class MyList<SubObject> extends ArrayList<Object>

with no success, If I use the subobject behind the class name it appears to work, but hides methods in the subobject class for some reason.

Any thoughts or suggestions on how to get this working right are appreciated.

+11  A: 

You need to specify a type for the ArrayList's type parameter. For generic type parameters, T is fairly common. Since the compiler doesn't know what a T is, you need to add a type parameter to MyList that can have the type passed in. Thus, you get:

public class MyList<T> extends ArrayList<T>

Additionally, you may want to consider implementing List and delegating to an ArrayList, rather than inheriting from ArrayList. "Favor object composition over class inheritance. [Design Patterns pg. 20]"

Adam Jaskiewicz
+3  A: 
public class MyList<T> 
    extends ArrayList<T>
{
}

MyList<SomeObject> list = new MyList<SomeObject>();

or

public class MyList
    extends ArrayList<SomeObject>
{
}

MyList list = new MyList();
TofuBeer
+1  A: 

You shouldn't extend ArrayList, extend AbstractList instead:

public class MyList<T> extends AbstractList<T> {
    public int size() {...}
    public T get(int index) {...}
}
Staale