Java Reference
In-Depth Information
10
11 System.out.println( "A list of cities in collection1:" );
12 System.out.println(collection1);
13
14 System.out.println( "\nIs Dallas in collection1? "
15 + collection1.contains( "Dallas" ));
16
17 collection1.remove( "Dallas" );
18 System.out.println( "\n" + collection1.size() +
19
contains?
size?
" cities are in collection1 now" );
20
21 Collection<String> collection2 = new ArrayList<>();
22 collection2.add( "Seattle" );
23 collection2.add( "Portland" );
24 collection2.add( "Los Angeles" );
25 collection2.add( "Atlanta" );
26
27 System.out.println( "\nA list of cities in collection2:" );
28 System.out.println(collection2);
29
30 ArrayList<String> c1 = (ArrayList<String>)(collection1.clone());
31 c1.addAll(collection2);
32 System.out.println( "\nCities in collection1 or collection2: " );
33 System.out.println(c1);
34
35 c1 = (ArrayList<String>)(collection1.clone());
36 c1.retainAll(collection2);
37 System.out.print( "\nCities in collection1 and collection2: " );
38 System.out.println(c1);
39
40 c1 = (ArrayList<String>)(collection1.clone());
41 c1.removeAll(collection2);
42 System.out.print( "\nCities in collection1, but not in 2: " );
43 System.out.println(c1);
44 }
45 }
clone
addAll
retainAll
removeAll
A list of cities in collection1:
[New York, Atlanta, Dallas, Madison]
Is Dallas in collection1? true
3 cities are in collection1 now
A list of cities in collection2:
[Seattle, Portland, Los Angeles, Atlanta]
Cities in collection1 or collection2:
[New York, Atlanta, Madison, Seattle, Portland, Los Angeles, Atlanta]
Cities in collection1 and collection2: [Atlanta]
Cities in collection1, but not in 2: [New York, Madison]
The program creates a concrete collection object using ArrayList (line 5), and invokes
the Collection interface's contains method (line 15), remove method (line 17), size
method (line 18), addAll method (line 31), retainAll method (line 36), and removeAll
method (line 41).
For this example, we use ArrayList . You can use any concrete class of Collection
such as HashSet , LinkedList , Vector , and Stack to replace ArrayList to test these
methods defined in the Collection interface.
 
Search WWH ::




Custom Search