Java Reference
In-Depth Information
21.7
Show the output of the following code:
import java.util.*;
public class Test {
public static void main(String[] args) {
LinkedHashSet<String> set1 = new LinkedHashSet<>();
set1.add( "New York" );
LinkedHashSet<String> set2 = set1;
LinkedHashSet<String> set3 =
(LinkedHashSet<String>)(set1.clone());
set1.add( "Atlanta" );
System.out.println( "set1 is " + set1);
System.out.println( "set2 is " + set2);
System.out.println( "set3 is " + set3);
}
}
21.8
Show the output of the following code:
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream( "c:\\test.dat" ));
LinkedHashSet<String> set1 = new LinkedHashSet<>();
set1.add( "New York" );
LinkedHashSet<String> set2 =
(LinkedHashSet<String>)set1.clone();
set1.add( "Atlanta" );
output.writeObject(set1);
output.writeObject(set2);
output.close();
ObjectInputStream input = new ObjectInputStream(
new FileInputStream( "c:\\test.dat" ));
set1 = (LinkedHashSet<String>)input.readObject();
set2 = (LinkedHashSet<String>)input.readObject();
System.out.println(set1);
System.out.println(set2);
output.close();
}
}
21.9
What will the output be if lines 6-7 in Listing 21.5 is replaced by the following
code:
Set<GeometricObject> set = new HashSet<>();
21.3 Comparing the Performance of Sets and Lists
Sets are more efficient than lists for storing nonduplicate elements. Lists are useful for
accessing elements through the index.
Key
Point
The elements in a list can be accessed through the index. However, sets do not support index-
ing, because the elements in a set are unordered. To traverse all elements in a set, use a foreach
loop. We now conduct an interesting experiment to test the performance of sets and lists.
Listing 21.6 gives a program that shows the execution time of (1) testing whether an element
 
 
 
Search WWH ::




Custom Search