tags:

views:

175

answers:

2

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?

+3  A: 

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.

mP
+3  A: 
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.

Stephen C
+1, but also a vote for the IllegalArguementException
akf
@akf: like I said ... it's a matter of opinion :-)
Stephen C