Alex Rivera | Logout

Java - How to subclass the generic ArrayList so that instances of MyArrayList<foo> will be subclasses of ArrayList<foo>?

Asked 2012-05-06T23:07:43.417
10

I want to keep my subclass generic, and all I want to change is the add(Object) method of ArrayList so that it won't add anything when you call arrayList.add(null) (the normal implementation of ArrayList will add the null; I want it to do nothing).

Edit
Report

1 Answer

10

This is an example where you should favor composition over inheritance.

Instead of extending ArrayList, you should create a class that has an ArrayList member field and exposes an add method that does the right thing.

Read Effective Java. Here is the example that describes this issue specifically.

answered 2012-05-06T23:11:33.900

Your Answer