Intermediate level · Module 2: The Java Collections Framework · Lesson 3 of 3
equals, hashCode and Safe Iteration
Make your own objects work correctly as Set elements and Map keys, and remove items safely while iterating.
In this lesson you will
- Implement equals and hashCode consistently
- Remove items safely with Iterator or removeIf
Key concepts
equals contracthashCodeConcurrentModificationExceptionIterator.remove
The lesson
HashSet and HashMap use hashCode to find a bucket and equals to compare items within it. If you override equals but not hashCode, two equal objects can land in different buckets and the set will contain duplicates. Always override both, using the same fields.
Objects.hash(name, phone) builds a suitable hashCode, and IntelliJ can generate equals and hashCode for you. Use fields that do not change while the object is in a set; changing a key field later makes the object impossible to find.
Removing from a list inside an enhanced for loop throws ConcurrentModificationException. Use an Iterator and call iterator.remove(), or use list.removeIf(condition), which is shorter and clearer.
Step by step
- Create a Customer class without equals/hashCode and add two equal customers to a HashSet.
- Observe the duplicate, then generate equals and hashCode.
- Repeat and confirm the set holds one customer.
- Remove inactive customers with removeIf.
Practice activity
Write a member register that stores members in a HashSet, rejects duplicates by phone number and removes expired members safely.
Expected result: Adding a member with an existing phone number has no effect, and expired members are removed without exceptions.
Check your understanding
-
What goes wrong if you override equals but not hashCode?
Show answer
Equal objects can be stored twice in hash-based collections because they get different hash codes.
-
Which method removes all list items that match a condition?
Show answer
removeIf.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.