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 can also raise an IllegalArgumentException, but a NullPointerException is the most appropriate IMO.
Note that it returns null incorrectly instead of throwing an exception. The java.util.Map API states that the result of the put operation is the previous display value for k or null if k has not been displayed before.
source share