File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question no :15, on generics fromk K&b

 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Arun Kumar Gaddam
Ranch Hand
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tree set implements SortedSet, so it sorts the strings that are put into it i.e "four","one","three","two" in alphabetical order...........
 
T Vergilio
Ranch Hand
Posts: 140
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
since this is a raw collection, aren't the elements stored as objects? How does TreeSet succeed in invoking compareTo on those elements?
 
Stephan van Hulst
Bartender
Pie
Posts: 4828
34
Chrome Netbeans IDE Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 227
Eclipse IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
T Vergilio
Ranch Hand
Posts: 140
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stephan and Aditya, it all makes sense now
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic