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).
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With