Hi, I encounter this question in the practice exam book:
import java.util.*;
public class Bucket1 {
public static void main(
String[] args) {
Set<String> hs = new HashSet<String>();
Set<String> lh = new LinkedHashSet<String>();
Set<String> ts = new TreeSet<String>();
List<String> al = new ArrayList<String>();
String[] v = {"3", "2", "A", "2"};
for(int i=0; i< v.length; i++) {
hs.add(v[i]); lh.add(v[i]); ts.add(v[i]); al.add(v[i]);
}
Iterator it = hs.iterator();
while(it.hasNext()) System.out.print(it.next() + " ");
System.out.println();
Iterator it2 = lh.iterator();
while(it2.hasNext()) System.out.print(it2.next() + " ");
System.out.println();
Iterator it3 = ts.iterator();
while(it3.hasNext()) System.out.print(it3.next() + " ");
System.out.println();
Iterator it5 = al.iterator();
while(it5.hasNext()) System.out.print(it5.next() + " ");
System.out.println();
} }
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.
Answer (for Objective 6.1):
C, D, and G are correct. The code is all legal and runs without exception. For HashSets,
iteration order is not guaranteed. For LinkedHashSets, iteration order equals insertion
order. For TreeSets, the default iteration order is ascending. For ArrayLists, iteration
order is by index, and when using add(), index “kind of” equals insertion order. Of course,
Sets don’t allow duplicates.
I have a question:
Since hash set does not guarantee any iteration order, the 6 possible outputs are : 132 / 123 / 321 / 312 / 213 / 231
linkedhash set 's output is 132
tree set's output is 123
array list output is 1 3 1 2
There will be 6 possible outputs totally as hash set's iteration order is not guaranteed.
So, choice C says 1 3 2 is only guaranteed to be in the output once. I think this is not true because when hash set's output is 1 32 and linkedhash set's output is 132 as well.
Choice D says 123 is only guaranteed to be in the output once. I think this is not true because hash set may output 123 while tree set output 123.
I think only G is correct.
What do you think?