File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question no :15, on generics fromk K&b Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question no :15, on generics fromk K&b" Watch "Question no :15, on generics fromk K&b" New topic

Question no :15, on generics fromk K&b

Dinesh Tahiliani
Ranch Hand

Joined: Aug 06, 2007
Posts: 486
TreeSet map = new TreeSet();
13. map.add("one");
14. map.add("two");
15. map.add("three");
16. map.add("four");
17. map.add("one");
18. Iterator it = map.iterator();
19. while (it.hasNext() ) {
20. System.out.print( + " " );
21. }
What is the result?
A. Compilation fails.
B. one two three four
C. four three two one
D. four one three two
E. one two three four one
F. one four three two one
G. An exception is thrown at runtime.
H. The print order is not guaranteed.

Answer --D.
How come ans is D, it should be B.
Can someone please shed some lights on this

Thanks<br />Dinesh
Arun Kumar Gaddam
Ranch Hand

Joined: May 05, 2007
Posts: 58
Tree set implements SortedSet, so it sorts the strings that are put into it i.e "four","one","three","two" in alphabetical order...........
Chandella Montero
Ranch Hand

Joined: Feb 18, 2011
Posts: 89
since this is a raw collection, aren't the elements stored as objects? How does TreeSet succeed in invoking compareTo on those elements?

OCA, OCP Java 6
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4624

TreeSet casts the objects to Comparable. If you were to add any objects that didn't implement Comparable, the tree would throw a ClassCastException.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227

Just to add onto that:

TreeSet has been doing this (casting to Comparable) in earlier versions too, when there was no generics. Also, a fun fact - when you add the first non-Comparable object to an empty TreeSet, it won't throw any exception. But, as soon as the second object is added, it needs to 'compare' them by casting them to Comparable. Hence, a ClassCastException is thrown.
Chandella Montero
Ranch Hand

Joined: Feb 18, 2011
Posts: 89
Thanks Stephan and Aditya, it all makes sense now
I agree. Here's the link:
subject: Question no :15, on generics fromk K&b
It's not a secret anymore!