Java OCA OCP Practice Question 2855

Question

Given the proper import(s), and this code in a method:

4.     List<String> x = new LinkedList<String>();   
5.     Set<String> hs = new HashSet<String>();  
6.     String[] v = {"a", "b", "c", "b", "a"};  
7.     for(String s: v) {  
8.       x.add(s);  hs.add(s);   /*from   ww  w. ja va2  s . c  om*/
9.     }  
10.     System.out.print(hs.size() + " " + x.size() + " ");  
11.     HashSet hs2 = new HashSet(x);  
12.     LinkedList x2 = new LinkedList(hs);  
13.     System.out.println(hs2.size() + " " + x2.size()); 

    

What is the result?.

  • A. 3 3 3 3
  • B. 3 5 3 3
  • C. 3 5 3 5
  • D. 5 5 3 3
  • E. 5 5 5 5
  • F. Compilation fails.
  • G. An exception is thrown at runtime.


B is correct.

Note

The code is all legal and runs without exception.

Since Sets don't allow duplicates, line 10's output, "3 5 ", should be no surprise.

When the Collection (LinkedList x) is passed into hs2's constructor, the Collection is trimmed so that no duplicates are created.




PreviousNext

Related