Meaningless Drivel is fun!*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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
Author

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( it.next() + " " );
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
Bartender

Joined: Sep 20, 2010
Posts: 3599
    
  14

TreeSet casts the objects to Comparable. If you were to add any objects that didn't implement Comparable, the tree would throw a ClassCastException.
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question no :15, on generics fromk K&b
 
Similar Threads
Casting example
generics
Set using generics
SCJP 1.5 Objective 6.2, hashCode() and equals()
Does equal() not have to be overridden