why HashTable don't allow null as key and value

why HashTable don't allow null as key and value? and other collection class allows null value?
Who is Participating?
n_sachin1Connect With a Mentor Commented:
Another example of a collection class that doesn't allow null is java.util.Vector.
These two classes were available in jdk1.0 and the implementors just chose to put this restriction, as they needed to synchronize access to the entries.
The internal implementation has changed (to retrofit the later developments like the java.util.Map interface), but these classes behave the same (as JDK1.0 to maintain the external contract).

You could look at the jdk sources available in src.zip for jdk1.0 and compare that with the jdk that you are using today. You'd see the difference yourself
Kevin CrossConnect With a Mentor Chief Technology OfficerCommented:
Hello Asheesh_Kumar,

If I am understanding you correctly, you are looking for a collection you can use that will not reject an object if it is null.  I don't believe List will.

Here are some references on the differences in the Java Collections API interfaces/implementations:

Each has a purpose as you will see, so just align the collection with your code need and should work out fine. ;)


Kevin CrossChief Technology OfficerCommented:
If you need specific functionality like a HashTable, you can look at HashMap in same grouping as it also implements the Map interface but allows null values.
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

sciuriwareConnect With a Mentor Commented:
Why should you assign a value of null?

How could you tell if null returned on a .get means "not found" or "null found"?

Kevin CrossChief Technology OfficerCommented:
Sometimes you are storing objects that need to have a null value.  I would also not recommend using for null key.  That eliminates the issue sciuriware presents as you know you have a found object by key you were searching on and it is just null at the moment.

Since the premise is that keys should unique, the HashMap will allow a null key but only once.
This question started with "Why".
'n_sachin1' gave some more info,
but 'mwvisa1' and me ('sciuriware') gave the "because" of SUN's implementation:

: the possible ambiguity in the collection's methods return value.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.