aspose file tools*
The moose likes Beginning Java and the fly likes Why does HashMap allow 'null' values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why does HashMap allow Watch "Why does HashMap allow New topic
Author

Why does HashMap allow 'null' values

Anasapurapu Vishnu
Greenhorn

Joined: Jan 18, 2008
Posts: 6
I have been wondering about this a little and wanted to know what could be the reason for allowing 'null' values into HashMap but not into HashTables.

Thanks
Vishnu
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
And you really think this is a topic for the Advanced forum?


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Remember that Hashtable came first. I think that there is rarely any reason to want null values or a null key in a hash table, and so the people who made Hashtable did not allow them. But later when the collections framework was expanded, the Map interface was written to be a bit more general. Even though the need for null values and the null key is rare, some people do use them occasionally. So Map was written to allow them (optionally), and the new HashMap implmentation definitely does allow them. However they didn't want to change the existing Hashtable implementation, so they left it alone.


"I'm not back." - Bill Harding, Twister
Anasapurapu Vishnu
Greenhorn

Joined: Jan 18, 2008
Posts: 6
Thank you very much for the reply, could you please let me know a situation where we would need to store 'null' values into a HashMap
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I can't really think of a good reason for this - personally I never use nulls in maps. Some other people do, and it doesn't really bother me, but I've never seen seen a need. Perhaps someone else can suggest a good example.
Dave Wingate
Ranch Hand

Joined: Mar 26, 2002
Posts: 262
Consider the example of using a Map to represent a row of data from a database. Databases often have nullable columns. Because Map allows null values, our map can have a key/value pair:
SOME_COLUMN_NAME -> null
This type of entry indicates that the table from which the data originated really does have a column named "SOME_COLUMN_NAME." If Map didn't allow null values, we couldn't (easily) use the map described above to distinguish between the following two scenarios:
- The backing table does not have a column named "SOME_COLUMN_NAME"
- The backing table does have a column named "SOME_COLUMN_NAME" but in this particular case the related value is null.
[ January 23, 2008: Message edited by: Dave Wingate ]

Fun programming etcetera!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why does HashMap allow 'null' values