Chapter 12. Sets
A set is a collection of items that cannot contain duplicates; adding an item that is already present in the set has no effect. The interface Set<E> has the same methods as those of Collection but it is defined separately in order to allow the contract of add (and addAll, which is defined in terms of add) to reflect this. The equals method is overridden: the Set contract states that a Set can only ever be equal to another Set, and then only if they are the same size and contain equal elements. The hashCode method is also overridden, as should always be the case when equals is overridden (see “Hash tables” in “Implementations”). The hash code of a Set is the sum of the hash codes of its elements.
Note
The code examples for this chapter can be found at:
https://github.com/MauriceNaftalin/JGC_2e_Book_Code/blob/main/src/main/java/org/jgcbook/chapter12
Let’s see an example of set operations in action. Returning to the to-do manager example introduced in “Using the Methods of Collection”, suppose that on Monday you have free time to carry out your telephone tasks. You can make the new collection of tasks for Monday by adding all your telephone tasks to the existing Monday tasks. Let mondayTasks and phoneTasks be as declared in Example 10-1.
Using a set, you can write:
Set<Task> phoneAndMondayTasks = new HashSet<>(mondayTasks); phoneAndMondayTasks.addAll(phoneTasks); assert phoneAndMondayTasks.equals(Set.of(logicCode, mikePhone, paulPhone)); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access