It's not a secret anymore!*
The moose likes Java in General and the fly likes Why HashMap allows to add one NULL key ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why HashMap allows to add one NULL key ?" Watch "Why HashMap allows to add one NULL key ?" New topic
Author

Why HashMap allows to add one NULL key ?

Cm Ananth
Ranch Hand

Joined: Oct 20, 2005
Posts: 44
Could someone explain me why HashMap allows to add one NULL key ? Because i don't see any practical use of adding NULL as the key and storing a value in it..

In which case we need to use NULL as a key? Please explain with some examples.

Thanks in advance..


By Ananth, Bangalore
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Why disallow it?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Cm Ananth
Ranch Hand

Joined: Oct 20, 2005
Posts: 44
I feel there won't be any use case for adding NULL as a key and store a value for it. I wonder why such a feature is allowed by java and some real world examples will help me to understand the use of this feature.

Thanks for your reply.
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Could be used to supply a default value I suppose. I'm imagining a situation where an application gives you a choice of options, and the result of these options are mapped with a HashMap. Now suppose this option choice is itself optional. The user hasn't selected anything therefore the choice is null, so return whatever value is in the Map with a null key.

Might not be how this is used, but I can't think of any benefit of preventing people using a null key?


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

One real life scenario where even a "null" can convey information.

I am working on a project where I have "jobs" (e.g. copy some data from some place to another). I also have a "schedule" which can be associated to the "jobs". The "schedule" contains information on at what time the job should be executed and when should it be repeated.
There is a simple check which we have put in. If the job schedule is null, we execute the job only once. Else we execute it as per schedule.


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Cm Ananth
Ranch Hand

Joined: Oct 20, 2005
Posts: 44
Thanks Paul & Maneesh..

Paul's example has given me some idea of where HashMap NULL keys can be used.

Any other examples also welcome
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37926
    
  22
Several people have given useful examples of when a null key is useful, but the real answer to the original question is that whoever designed the class thought it would be most useful like that.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by CM Ananth:
I feel there won't be any use case for adding NULL as a key and store a value for it. I wonder why such a feature is allowed by java and some real world examples will help me to understand the use of this feature.


I think the question should be reverted: how would disallowing null as a key be useful?

Why actively disallow something just because we can't yet think of a case where it would be useful?
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3419
    
  12
Implementing your own version of HashMap that doesn't allow a null is easy by just extending or wrapping the HashMap class and putting some extra checking in. Whereas creating your own class that allowed nulls if HashMap didn't allow them would be a little more difficult.


Joanne
Brian Carlisle
Greenhorn

Joined: Oct 30, 2012
Posts: 19
Hello - i was running some basic code tests to try and do this and keep getting a runtime exception whenever i add another element to the Map/Set after putting a null key initially. Seems that it always fails on the equals method when comparing the current object being inserted to the previous null entry. This makes sense so i am curious how this is implemented in the real world. A bit confused.

Any thoughts? Thanks.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3419
    
  12
Brian Carlisle wrote:Hello - i was running some basic code tests to try and do this and keep getting a runtime exception whenever i add another element to the Map/Set after putting a null key initially. Seems that it always fails on the equals method when comparing the current object being inserted to the previous null entry. This makes sense so i am curious how this is implemented in the real world. A bit confused..

Can you show us the code you are using and what exception you are getting. It works fine for me.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4165
    
  21

Specifically, look at the equals() method of the class you are putting in to the map. I would suspect that is where the exception is coming from.


Steve
Brian Carlisle
Greenhorn

Joined: Oct 30, 2012
Posts: 19
Sure - taken from the SCJP book. I added the null entry to see what would happen. Also tried changing the int to String for size and using equals() but no luck. The same happens when i convert the code to use a LinkedHashMap.

It makes sense to me logically why the exception is thrown.

Brian Carlisle
Greenhorn

Joined: Oct 30, 2012
Posts: 19
Yes it is most certainly in the equals method. Can you show me a simple example of this working? Much appreciated.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4165
    
  21

Brian Carlisle wrote:

This equals() method isn't very good. The error is on line 3 (in the if condition). You assume the Object being compared to (o) is not null, you dereference it without first checking if it was nulll. So this would fail. You need to do a first check. A typical equals() method would be like this:


<edit>Forgot the case where other might be of a different type. This is one way of checking that. Another is to use instanceof, but there is a difference in semantics between the two options... I chose to check classes for equality</edit>
Brian Carlisle
Greenhorn

Joined: Oct 30, 2012
Posts: 19
Thanks Steve!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

I usually follow that flow but shorten it a bit:
I also wonder why in hashCode you divide the size by 5. Why not simply return size itself? It's an int, so it's a valid value.

Edit: I just saw that Steve's example uses Turtle.class to compare to. I prefer not to use one fixed class except if the class is final (in which case I use instanceof). Using getClass() instead allows sub classes to still have a valid equals method. Let's say you have class SnappingTurtle extends Turtle, then in Steve's example a new SnappingTurtle(5) will be equal to a new Turtle(5), which I disagree with. In my example, the two will be unequal even though they have the same size.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Brian Carlisle
Greenhorn

Joined: Oct 30, 2012
Posts: 19
Yes the hashcode method is definately bizarre. But its straight from the SCJP test book. Prepping for the exam and want to be prepared for anything.

Thanks.
Anindya Roy
Ranch Hand

Joined: May 11, 2014
Posts: 67
Because HashMap allows only unique keys. Repetition of the same value for different keys are allowed.


http://www.webtuts.in
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why HashMap allows to add one NULL key ?
 
Similar Threads
Hashtable and Hashmap Doubt
How to access Null key value of an HashMap
HashMap
HashMap
Hashtable doesn't allow null value and HashMap allows only one null as key