0

The OpenJDK implementation of AbstractSet throws a NullPointerException when you pass a null value to removeAll.

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/AbstractSet.java

    public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);

e.g.

    Set<String> parent = new HashSet<String>();
    Set<String> children = null;
    parent.removeAll(children);

Results in

Exception in thread "main" java.lang.NullPointerException
    at java.util.AbstractSet.removeAll(AbstractSet.java:152)

What is the architectural logic behind this?

Why wouldn't it do a null check and return modified = false instead of throwing a NullPointerException?

What is the benefit in this case between differentiating between null and an empty set?

EDIT:

I know the interface specifies it. You can ask the same question about the interface. The point of the question is that removing nothing from something leaves you with the original. There doesn't seem to be a logical reason for throwing a NullPointerException.

For those that say any null should be fixed, that isn't a logical reason for throwing a NullPointerException in this case.

It isn't a duplicate question of What is a NullPointerException, and how do I fix it? because I am asking about the architectural design of a specific method and not asking what a NPE is.

Community
  • 1
  • 1
opticyclic
  • 7,412
  • 12
  • 81
  • 155
  • 2
    [This is even mandated by the `Set` interface](https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#removeAll-java.util.Collection-) – Thomas Kläger Jan 18 '17 at 16:51
  • 1
    If you've got unexpected `null`s flying around in your code (as in, ones that you haven't checked for before calling `removeAll`), if it's not *this* which throws an NPE, it'll be something else, sooner or later. Better to fail noisily sooner, then you'll fix it. – Andy Turner Jan 18 '17 at 16:53
  • `null` almost certainly represents an _error in the programming_, and the sooner you find out the better. Throwing exceptions as early as possible is generally good programming practice. – Louis Wasserman Jan 18 '17 at 18:27

0 Answers0