2010/09/22

NullPointerException Confusion

It's good to know that our field is called Computer Science. We're scientists. We like facts, laws and rules... Yeah, right. You think that if you've learned the basics of Data Structures, Algorithms and other courses in your B.Sc. it would prepare you for the real world. Nope. It's craaaaazy out there.

Today I had a real head-scratching moment when a completely innocent 'hashtable.put(key,val)' started giving me NullPointerException. Now, since I do know how hashes work, all I checked was - is the table itself null ? Nope, it's good. So what the hell?

Here comes the scary part:

put

public V put(K key,
             V value)
Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null.The value can be retrieved by calling the get method with a key that is equal to the original key.
Specified by:
put in interface Map<K,V>
Specified by:
put in class Dictionary<K,V>

Parameters:
key - the hashtable key.
value - the value.
Returns:
the previous value of the specified key in this hashtable, or null if it did not have one.
Throws:
NullPointerException - if the key or value is null.
Apparently the usual approach is not good for the Java folk. They don't want no stinking nulls in their precious hashes!
The reasoning behind the idiocity is this - the default behavior of get() method in hashtable is to return null if key was not found. So when the designers of the API chose that wrong path, they had to follow it up with a wronger path, since they couldn't distinguish between a null from 'no key found' and 'null found  as a value'.

I hate people.

No comments:

Post a Comment