Chapter 13. Sets

A set is a collection of items that cannot contain duplicates; adding an item if it is already present in the set has no effect. The Set 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. Returning to the task manager example in the previous chapter, suppose that on Monday you have free time to carry out your telephone tasks. You can make the appropriate collection by adding all your telephone tasks to your Monday tasks. Let mondayTasks and phoneTasks be as declared in Example 12-1. Using a set (again choosing a conveniently common implementation of Set), you can write:

Set<Task> phoneAndMondayTasks = new TreeSet<Task>(mondayTasks);
phoneAndMondayTasks.addAll(phoneTasks);
assert phoneAndMondayTasks.toString().equals(
  "[code logic, phone Mike, phone Paul]");

This works because of the way that duplicate elements are handled. The task mikePhone, which is in both mondayTasks and phoneTasks, appears as intended, only once, inphoneAndMondayTasks—you definitely don’t want to have to do all such tasks twice over!

Implementing Set

When we used the methods of Collection in the examples of Chapter 12, we emphasized that they would work with any implementation of Collection. What if we had decided that we would use one of the Set implementations from the Collections Framework? We would have had to choose between the various concrete implementations ...

Get Java Generics and Collections 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.