Java Reference
In-Depth Information
B
A
A B
Union
A B
Intersect
A - B
Difference
Figure 11.3
Set operation Venn diagrams
However, a more elegant way to perform this calculation is to compute a union
between the sets. The union of two sets A and B is the set of all elements contained in
either A, B, or both. Union is an example of a set operation . Other examples of set
operations are intersection (the set of all elements that are in both A and B) and
difference (the set of all elements that are in A but not in B). Many set operations
combine two sets to produce a new set as their result.
Set operations are often depicted by drawings called Venn diagrams, which depict
sets as circles and set operations as shaded overlapping between the circles. Figure
11.3 shows some examples.
You can write code to perform set operations by calling methods whose names end
with “All” using the relevant pair of sets. Table 11.4 summarizes which methods cor-
respond to which set operations.
Table 11.4
Common Set Operations, Given Two Sets A and B
Set operation
Method
Description
union
Set of all elements that are in A, B, or both
addAll
intersection
Set of all elements that are in both A and B
retainAll
difference
Set of all elements that are in A but not in B
removeAll
superset, subset
Returns true if A is a superset of (contains all
elements of ) B
containsAll
 
Search WWH ::




Custom Search