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, in phoneAndMondayTasksyou definitely don't want to have to do all such tasks twice over!




Java Generics and Collections
Java Generics and Collections
ISBN: 0596527756
EAN: 2147483647
Year: 2006
Pages: 136

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net