Java Reference
In-Depth Information
7
8
public class Algorithms2
9
{
10
public static void main(String[] args)
11
{
12
// initialize list1 and list2
13
String[] colors = { "red" , "white" , "yellow" , "blue"} ;
14
List<String> list1 = Arrays.asList(colors);
15
ArrayList<String> list2 = new ArrayList<>();
16
17
list2.add( "black" ); // add "black" to the end of list2
18
list2.add( "red" ); // add "red" to the end of list2
19
list2.add( "green" ); // add "green" to the end of list2
20
21
System.out.print( "Before addAll, list2 contains: " );
22
23
// display elements in list2
24
for (String s : list2)
25
System.out.printf( "%s " , s);
26
27
Collections.addAll(list2, colors); // add colors Strings to list2
28
29
System.out.printf( "%nAfter addAll, list2 contains: " );
30
31
// display elements in list2
32
for (String s : list2)
33
System.out.printf( "%s " , s);
34
35
// get frequency of "red"
int frequency = Collections.frequency(list2, "red" );
System.out.printf(
"%nFrequency of red in list2: %d%n" , frequency);
36
37
38
39
40
// check whether list1 and list2 have elements in common
boolean disjoint = Collections.disjoint(list1, list2);
41
42
43
System.out.printf( "list1 and list2 %s elements in common%n" ,
44
(disjoint ? "do not have" : "have" ));
45
}
46
} // end class Algorithms2
Before addAll, list2 contains: black red green
After addAll, list2 contains: black red green red white yellow blue
Frequency of red in list2: 2
list1 and list2 have elements in common
Fig. 16.13 | Collections methods addAll , frequency and disjoint . (Part 2 of 2.)
Line 14 initializes list1 with elements in array colors , and lines 17-19 add String s
"black" , "red" and "green" to list2 . Line 27 invokes method addAll to add elements
in array colors to list2 . Line 36 gets the frequency of String "red" in list2 using
method frequency . Line 41 invokes method disjoint to test whether Collection s list1
and list2 have elements in common, which they do in this example.
Search WWH ::




Custom Search