Why can't HashSet
also be an answer for the following question? When I tested the code, both HashSet
and TreeSet
gave the same output, but the correct answer it seems is TreeSet
. The code is below:
import java.util.*;
public class Example {
public static void main(String[] args) {
// insert code here
set.add(new Integer(2));
set.add(new Integer(1));
System.out.println(set);
}
}
Which code, inserted at line 4, guarantees that this program will output [1, 2]?
Set set = new TreeSet();
Set set = new HashSet();
Set set = new SortedSet();
List set = new SortedList();
Set set = new LinkedHashSet();