Java Reference
In-Depth Information
For example, we could rewrite the
totalElements
code to use a union with the
addAll
method:
// returns the number of elements contained in both set1 and set2
public static int totalElements(Set<String> set1, Set<String> set2) {
Set<String> union = new HashSet<String>(set1);
union.addAll(set2);
return union.size();
}
It's important to note that the set operations in Java modify the existing sets on
which you call them, rather than creating new sets for you. Notice that in the preceding
code, we initialize a new
HashSet
that contains all the elements from
set1
and then
add the contents of
set2
to the new set, rather than combining
set1
and
set2
directly.
We do this because the caller might not want us to disturb the sets' original contents.
Consider the task of writing a lottery program. The program should randomly gener-
ate a winning lottery ticket, then prompt the player to enter lotto numbers. Depending
on how many numbers match, the player wins various prizes.
Sets make excellent collections for storing the winning lotto numbers and the
player's numbers. They prevent duplicates, and they allow us to efficiently test
whether a number in one set exists in the other. These features will help us to count
the number of winning numbers the player has entered.
The following code uses a
Random
object to initialize a set of six winning lottery
numbers between 1 and 40. The code uses a
while
loop because the same number
might be randomly generated more than once:
Set<Integer> winningNumbers = new TreeSet<Integer>();
Random r = new Random();
while (winningNumbers.size() < 6) {
int number = r.nextInt(40) + 1;
winningNumbers.add(number);
}
Once the program has generated the winning number set, we'll read the player's
lottery numbers into a second set. To figure out how many numbers the player has chosen
correctly, we could search the winning number set to see whether it contains each num-
ber from the ticket. However, a more elegant way to perform this test is to determine the
intersection between the winning numbers set and the player's ticket set. The following
code creates the intersection of the player's ticket and the winning numbers by copying
the ticket and then removing any elements from it that aren't winning numbers:
// find the winning numbers from the user's ticket
Set<Integer> intersection = new TreeSet<Integer>(ticket);
intersection.retainAll(winningNumbers);
Search WWH ::
Custom Search