Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hash map

 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it SCJP book by K Siera & Berts Bates it is written that "hash map can have one null key & multiple null values" null values is alright but how can it has null key. then can values be retrieved from it.

please explain
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sweety sinha wrote: "hash map can have one null key & multiple null values" null values is alright but how can it has null key. then can values be retrieved from it.

Had you tried to put a "null" value as a key in HashMap instance, lets try it and tell us whether you're able to fetch the respective "value" from it ?

 
Ninad Kulkarni
Ranch Hand
Posts: 802
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashMap object hold key and it's corresponding value.

See the following non-generic code example



Ouput is English not Maths.
The second put method call changes value to English. Initially null key point to Maths but now point to English.
In such a way HashMap have unique keys and multiple values. Multiple values may be same or different but keys must have unique values.

I hope this clears
 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys for quick response
 
David Marco
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And watch out for TreeMap and SortedMap, which NOT ALLOWS for null keys (NullPointerException will arise at runtime).

Greetings.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to point that a TreeMap can have a null key, as long as the TreeMap is constructed using a Comparator which handles keys with the null value.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic