Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parameterize an extended Collection

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.

like image 556
Sheldon Ross Avatar asked Dec 06 '22 06:12

Sheldon Ross


2 Answers

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]"

like image 160
Adam Jaskiewicz Avatar answered Dec 07 '22 20:12

Adam Jaskiewicz


public class MyList<T> 
    extends ArrayList<T>
{
}

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

or

public class MyList
    extends ArrayList<SomeObject>
{
}

MyList list = new MyList();
like image 28
TofuBeer Avatar answered Dec 07 '22 20:12

TofuBeer