Java: Treemap - disable null?

Is there a way to prevent the treemap from returning to zero or do I need to do a check every time I enter something?

+4
source share
2 answers

Write a delegate set that wraps the real set and adds a guard to Set.add ().

If you provide a Comparator for a TreeSet, you can also complain that either of the two inputs to Comparator is null.

+4
source
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.

+10
source

All Articles