How to parameterize an extended collection

I am trying to extend the ArrayList class without much success. I want to expand it and be able to parameterize it.

So you have something like

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

I want to

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

A simple ArrayList extension does not work.

 public class MyList extends ArrayList ... 

When I try to use it, I get an error

MyList is not a generic type; This cannot be parameterized with <SomeObject> arguments

I tried the options

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

without success. If I use a subobject behind the class name, it seems to work, but for some reason hides methods in the subobject.

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

+4
source share
3 answers

You need to specify the type of the ArrayList parameter. For typical type T parameters, it is quite common. Since the compiler does not know what T , you need to add a type parameter to MyList , which may be of the type that was passed. So you get:

 public class MyList<T> extends ArrayList<T> 

Alternatively, you might consider embedding List and delegating an ArrayList rather than inheriting from an ArrayList . "Use object composition over class inheritance. [Design Patterns p. 20]"

+12
source
 public class MyList<T> extends ArrayList<T> { } MyList<SomeObject> list = new MyList<SomeObject>(); 

or

 public class MyList extends ArrayList<SomeObject> { } MyList list = new MyList(); 
+3
source

You should not extend ArrayList, instead AbstractList :

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

All Articles