Java Reference
In-Depth Information
Display 16.6 HashSet<T> Class Demo (part 2 of 3)
25
System.out.println("Contents of set round: ");
26
outputSet(round);
27
System.out.println("\nContents of set green: ");
28
outputSet(green);
29
System.out.println("\nball in set 'round'? " +
30
round.contains("ball"));
31
System.out.println("ball in set 'green'? " +
32
green.contains("ball"));
33
System.out.println("\nball and peas in same set? " +
34
((round.contains("ball") &&
35
(round.contains("peas"))) ||
36
(green.contains("ball") &&
37
(green.contains("peas")))));
38
System.out.println("pie and grass in same set? " +
39
((round.contains("pie") &&
40
(round.contains("grass"))) ||
41
(green.contains("pie") &&
42
(green.contains("grass")))));
43
// To union two sets we use the addAll method.
44
HashSet<String> setUnion = new HashSet<String>(round);
45
round.addAll(green);
46
System.out.println("\nUnion of green and round:");
47
outputSet(setUnion);
48
// To intersect two sets we use the removeAll method.
49
HashSet<String> setInter = new HashSet<String>(round);
50
setInter.removeAll(green);
51
System.out.println("\nIntersection of green and round:");
52
outputSet(setInter);
53
System.out.println( );
54
}
55
}
Sample Dialogue
Contents of set round:
grapes pie ball peas
Contents of set green:
grass garden hose grapes peas
(continued)
 
Search WWH ::




Custom Search