Java: Treemap - forbid null?
Question
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?
Solution
Write up a delegating Set that wraps the real Set and add a guard to Set.add().
If you are providing a Comparator to the TreeSet you can also complain if either of thw two inputs to the Comparator are null.
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow