Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Treemap - forbid null?

Tags:

java

null

treemap

Is there a way to prevent a treemap from accepting null values, or do I need to do a check every time I enter something?

like image 835
Nick Heiner Avatar asked Dec 10 '22 19:12

Nick Heiner


1 Answers

public class NonNullTreeMap<K,V> extends TreeMap<K,V> {
    @Override
    public V put(K k, V v) {
         if (v == null) {
             throw new NullPointerException("value is null");
         }
         return super.put(k,v);
    }
}

You could also throw an IllegalArgumentException, but a NullPointerException is most appropriate IMO.

Note that it is incorrect to return null instead of throwing an exception. The java.util.Map API states that the result of the put operation is the previous value of the mapping for k, or null if k was not previously mapped.

like image 103
Stephen C Avatar answered Dec 20 '22 14:12

Stephen C