Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 582
Tim Avatar asked May 06 '12 23:05

Tim


2 Answers

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;
    }
}
like image 82
fbafelipe Avatar answered Nov 07 '22 05:11

fbafelipe


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.

like image 39
Amir Afghani Avatar answered Nov 07 '22 05:11

Amir Afghani