HashSet Internals and Duplicates
35 min · Intermediate
A HashSet is a HashMap in disguise: each element is stored as a key, and every value is the same dummy object. So everything you know about HashMap, buckets, hashCode, equals and load factor, explains how a set rejects duplicates.
Topics in this lesson
- HashSet is a HashMap with a dummy value
- How duplicates are detected: hashCode, then equals
- HashSet vs LinkedHashSet vs TreeSet
- Predict the output: custom objects in a set
- Coding question: remove duplicates while keeping order
Interview questions this lesson answers
- How does HashSet work internally?
- How does HashSet detect a duplicate?
- Why must equals and hashCode be overridden together?
- What does add return?
- Can a HashSet contain null?
- What is the time complexity of add, remove and contains in a HashSet?
- What is the difference between HashSet, LinkedHashSet and TreeSet?
- How does TreeSet check duplicates?
- What does consistent with equals mean for a comparator?
- What happens if you change a field of an object after adding it to a HashSet?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.