Java Reference
In-Depth Information
14 set.add( "New York" );
15
16 System.out.println(set);
17
18 // Display the elements in the hash set
19 for (String s: set) {
20 System.out.print(s.toUpperCase() + " " );
21 }
22 }
23 }
traverse elements
[San Francisco, New York, Paris, Beijing, London]
SAN FRANCISCO NEW YORK PARIS BEIJING LONDON
The strings are added to the set (lines 9-14). New York is added to the set more than once, but
only one string is stored, because a set does not allow duplicates.
As shown in the output, the strings are not stored in the order in which they are inserted
into the set. There is no particular order for the elements in a hash set. To impose an order
on them, you need to use the LinkedHashSet class, which is introduced in the next section.
Recall that the Collection interface extends the Iterable interface, so the elements in
a set are iterable. A foreach loop is used to traverse all the elements in the set (lines 19-21).
Since a set is an instance of Collection , all methods defined in Collection can be used
for sets. Listing 21.2 gives an example that applies the methods in the Collection interface
on sets.
L ISTING 21.2
TestMethodsInCollection.java
1 public class TestMethodsInCollection {
2
public static void main(String[] args) {
3
// Create set1
4
java.util.Set<String> set1 = new java.util.HashSet<>();
create a set
5
6 // Add strings to set1
7 set1.add( "London" );
8 set1.add( "Paris" );
9 set1.add( "New York" );
10 set1.add( "San Francisco" );
11 set1.add( "Beijing" );
12
13 System.out.println( "set1 is " + set1);
14 System.out.println(set1.size() + " elements in set1" );
15
16 // Delete a string from set1
17 set1.remove( "London" );
18 System.out.println( "\nset1 is " + set1);
19 System.out.println(set1.size() + " elements in set1" );
20
21
add element
get size
remove element
// Create set2
22
java.util.Set<String> set2 = new java.util.HashSet<>();
create a set
23
24 // Add strings to set2
25 set2.add( "London" );
26 set2.add( "Shanghai" );
27 set2.add( "Paris" );
28 System.out.println( "\nset2 is " + set2);
29 System.out.println(set2.size() + " elements in set2" );
add element
 
 
Search WWH ::




Custom Search