Welcome Guest | Sign in | Register
Collections - Discussion Page For Q.2567 | Java Programming Questions and Answers | Java Programming Free Online-Tests | LucentBlackBoard | LucentBlackBoard.com

Home > Java Programming > Collections > Questions and Answers

Q: What is the output for the below code?

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Test {
public static void main(String... args) {
Set s = new TreeSet();
s.add("7");
s.add(9);
Iterator itr = s.iterator();
while (itr.hasNext())
System.out.print(itr.next() + " ");
}
}
A. Compile error B. Runtime Exception
C. 79 D. None of the above

Answer and Explanation

Answer:Runtime Exception

Explanation:
Without generics, the compiler does not know what type is appropriate for this
TreeSet, so it allows everything to compile. But at runtime the TreeSet will try to sort the
elements as they are added, and when it tries to compare an Integer with a String it will
throw a ClassCastException.

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be
cast to java.lang.Integer.

Comment on this Question

Name:

Loading...




Partner Sites
LucentBlackBoard.com                  SoftLucent.com                  LucentJobs.com
All rights reserved © 2012-2015 SoftLucent.