Skip to main content

Internal Working of HashSet

Learn Internal Working of HashSet (Internal Working, Collection Framework) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

The big idea: a HashSet is a HashMap A HashSet does not have its own storage . Inside it holds a HashMap ; every element you add becomes a key of that map, and the value is always the same dummy object. So "a Set has no duplicates" is really "a Map has no duplicate keys". Field: private transient HashMap<E, Object> map; Field: private static final Object PRESENT = new Object(); (the shared dummy value) add(e) is map.put(e, PRESENT) == null : it returns true only if the key was new. contains(e) is map.containsKey(e) ; remove(e) is map.remove(e) == PRESENT . Everything you learnt about HashMap...

More lessons in Internal Working