Java OCA OCP Practice Question 3050

Question

Given:

1. import java.util.*;  
2. public class Main {  
3.   public static void main(String[] args) {  
4.     Set<String> hs = new HashSet<String>();  
5.     Set<String> lh = new LinkedHashSet<String>();  
6.     Set<String> ts = new TreeSet<String>();  
7.     List<String> al = new ArrayList<String>();  
8.     String[] v = {"1", "3", "1", "2"};  
9.     for(int i=0; i< v.length; i++) {  
10.       hs.add(v[i]);  lh.add(v[i]);  ts.add(v[i]);  al.add(v[i]);  
11.     }  //from   ww w  .j  a  v a2  s . com
12.     Iterator it = hs.iterator();  
13.     while(it.hasNext()) System.out.print(it.next() + " ");   
14.     Iterator it2 = lh.iterator();  
15.     while(it2.hasNext()) System.out.print(it2.next() + " ");  
16.     Iterator it3 = ts.iterator();  
17.     while(it3.hasNext()) System.out.print(it3.next() + " ");   
18.     Iterator it5 = al.iterator();  
19.     while(it5.hasNext()) System.out.print(it5.next() + " ");    
20. } }    

Which statements are true? (Choose all that apply.)

  • A. An exception is thrown at runtime.
  • B. Compilation fails due to an error on line 18.
  • C. "1 3 2" is only guaranteed to be in the output once.
  • D. "1 2 3" is only guaranteed to be in the output once.
  • E. "1 3 2" is guaranteed to be in the output more than once.
  • F. "1 2 3" is guaranteed to be in the output more than once.
  • G. "1 3 1 2" is guaranteed to be in the output at least once.
  • H. Compilation fails due to error(s) on lines other than line 18.


C, D, and G are correct.

Note

The code is all legal and runs without exception.

For HashSet, iteration order is not guaranteed.

For LinkedHashSet, iteration order equals insertion order.

For TreeSet, the default iteration order is ascending.

For ArrayList, iteration order is by index, and when using add(), index "kind of" equals insertion order.

Sets don't allow duplicates.




PreviousNext

Related