Reputation: 437
I know all those weird philosophical reasons why null instances are allowed in every collection
But unlike in lists,position of sets' (even maps, too) elements depend upon the hashcode of element being added thereby on the element itself (barring exceptions like LinkedHashSet
where insertion order is preserved)
So while computing hashcode of element being added to collection and if that element is presumed to be null shouldn't it throw NPE ?
null.hashCode()
Does it have some type of null-checking
First i thought System.out.println(setReference) too should generate NPE if there is a null, but after quite a bit research i found that actual method that is called is static valueOf(Object obj) rather than toString() method which is null safe from what is stated in java docs, i have finally been to clear my head about it ...
but this still haunts me, i know i am being little obsessive about tiny details but i have to 'cause currently i am preparing for OCAJP 8 so i risked downrating to get credible explanation since i didn't find anything in java docs pertaining to this...
so what operations in sets are null-safe, a comprehensive answer is appreciated.
Upvotes: 3
Views: 1255
Reputation: 311948
null
are handled explicitly. If you look at HashSet
's implementation, it's basically a HashMap
where all the keys point to the same (dummy) value. If you drill down to the way HashMap
calculates the hash code for a key, you'd find this method (code taken from OpenJDK 1.8.0_92-b14, although I sincerely doubt it will differ in any other JDK):
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
So, to make a long story short, HashSet
s and HashMap
s explicitly handle null
s and treat their hash as 0.
Upvotes: 6