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
Joined: Oct 20, 2005
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.
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?
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.
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.
Joined: Jul 11, 2001
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?
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.