Chapter 11. 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 Set<E> interface 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 be changed in this way. For example, returning to the task manager, 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 ???. Using a set, you can write:

Set<Task> phoneAndMondayTasks = new HashSet<>(mondayTasks);
phoneAndMondayTasks.addAll(phoneTasks);
assert phoneAndMondayTasks.equals(Set.of(logicCode, mikePhone, paulPhone));

This works because of the way that duplicate elements are handled. The task mikePhone, although ...

Get Java Generics and Collections, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.