Issue
I am trying to create class that extends the java.util.ArrayList
by overriding
the add method in the following way: it does nothing if the object to be added already exists
in the collection; otherwise it calls the add method in the super class to add the object into
the collection.
My code look like that so far but it gives a NullPointerException
:
import java.util.ArrayList;
public class myArrayList<E> extends ArrayList<E> {
public ArrayList<E> mylist;
@Override
public boolean add(E e) {
if (!mylist.contains(e)) {
super.add(e);
return true;
} else {
return false;
}
}
}
public static void main(String[] args) {
myArrayList<Integer> listing = new myArrayList<Integer>();
listing.add(4);
listing.add(4);
for (int i = 0; i < listing.size(); i++) {
System.out.println(listing.get(i));
}
}
Solution
While we can't be sure this is your problem (unless you show us the stacktrace!), it looks like an NPE is likely to occur in this line:
if (!mylist.contains(e)) {
because mylist
is never initialized.
In fact, if you are trying to extend ArrayList
rather than create a list wrapper, the mylist
variable should not exist at all. The list state is in the superclasses private variables. Instead, the add
method should probably be written like this:
@Override
public boolean add(E e) {
if (!super.contains(e)) {
return super.add(e); // See note
} else {
return false;
}
}
Note: in general, you should return whatever the superclass returns here. However, when the superclass is ArrayList
, we know1 that add
will return true
, so this is only "saving" a line of code. There might be marginal performance difference, depending on how smart the JIT optimizer is.
1 - We know because the ArrayList.add
javadoc specifically states that true
is returned.
But this looks like you are trying to create a "set-like" list class. There could be better alternatives; e.g. LinkedHashSet
has a defined iteration order, and addition is O(1)
rather than O(N)
. (Admittedly, LinkedHashSet
uses a lot more memory, and it has no efficient equivalent to the positional List.get(int)
method.)
Answered By - Stephen C