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

arraylist, generics, java

Solution

You really should favor composition over inheritance in this case, because if you forget to override one of the methods from ArrayList which add/change an element (you could forget to override set, for example), it will still be possible to have null elements.

But since the question was about how to subclass ArrayList, here is how you do it:

import java.util.ArrayList;

public class MyArrayList<T> extends ArrayList<T> {
    public boolean add(T element) {
        if (element != null) return super.add(element);
        return false;
    }
}

Problem

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).

Original source