HashSet:This class implements the Set interface, backed by a hash table (actually a HashMap instance).
While adding elements into HashSet i never specify the key and offcourse it does not make sense to specify the key since its a set. I am wondering since the HashSet is implemented via a HashMap instance , what would be the key that would be used to put data into HashSet.
The answer is they key is a the value that is passed into the the hashset. For example
HashSet<
String> names = new HashSet<String>();
names.add("Deepak");
Internally since the HashSet is implemented by a HashMap instance , and HashMap requires a key and value. So here the key = "Deepak" and value = "new Object()". The Value is a dummy object.Which is infact a static constant so that each add operation does not create a dummy instances of Object.
Hence names.add("Deepak");
gets converted to
internalHashMap.put("Deepak",object);
Here object defined as
private static final Object object = new Object();
I had this doubt but after reading a bit i got the solution as well. Hence i thought i would post it.