Given:
import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class Main { public static void before() { Set set = new TreeSet(); set.add("2"); set.add(3);//from w ww .j a va 2 s .c o m set.add("1"); Iterator it = set.iterator(); while (it.hasNext()) System.out.print(it.next() + " "); } public static void main(String args[]) { before(); } }
Which statements are true?
before()
method will print 1 2before()
method will print 1 2 3before()
method will print three numbers, but the order cannot be determinedbefore()
method will not compilebefore()
method will throw an exception at runtimeE is correct.
You can't put both Strings and ints into the same TreeSet.
Without generics, the compiler has no way of knowing what type is appropriate for this TreeSet, so it allows everything to compile.
At runtime, the TreeSet will try to sort the elements as they're added, and when it tries to compare an Integer with a String, it will throw a ClassCastException.
Note that although the before()
method does not use generics, it does use autoboxing.
Watch out for code that uses some new features and some old features mixed together.