I have some questions about Java Collection
objects...
- When we add objects to a collection like
HashSet
orHashMap
, how the the objects internally stored? - Why doesn't
Hashtable
allownull
values?
I have some questions about Java Collection
objects...
HashSet
or HashMap
, how the the objects internally stored?Hashtable
allow null
values?You're not adding an object to the collection. You're adding a reference.
As for why HashTable
doesn't allow null
keys and values - it's just a design decision; in some cases it's helpful to disallow null keys, while in others it's annoying. HashMap
does allow for both null keys and values, for example. There are various reasons for prohibiting nulls:
Usually a null key or a null value indicates a programming error in the calling code. Rejecting this at the point of insertion makes it far easier to find the error than waiting until the code fetches a value and then has an unexpected null.
If you know that values in a map can't be null, then you don't need to do a separate check for containment and then fetch: you can fetch, and if the result is null, you know the key was missing.
It takes a bit more work to handle null keys in the map implementation. While null values can sometimes be useful, null keys almost never are.
Hashtable does not allow null values because it uses the equals and hashcode methods of the objects added to it