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