Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inquisition Question

 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Choose all that apply:
A) Compiles with warning
B) A runtime exception occurs
C) Compiles without warning
D) Only one test object is added, Other one is considered duplicate
E) TreeSet can only accept objects of type test.

Answer is : B,C & E

my question is why will there be a runtime exception.
 
Ankit Garg
Sheriff
Posts: 9529
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hint: The class test implements Comparator and not Comparable...
 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so that means, Comparator interface can only be implemented by a class separate from the class whose instances are to be sort.

am I right?
 
G Venu
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TreeSet collection object created with default constructor takes elements that implement Comparable interface only.
When the code tries to insert elements that violate this constraint, ClassCastException will be thrown.

To me the code should not even compile.

http://java.sun.com/javase/7/docs/api/java/util/TreeSet.html#TreeSet()
 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
G Venu wrote:TreeSet collection takes elements that implement Comparable interface only. When the code tries to insert elements that violate this constraint, ClassCastException will be thrown.



Got this point.


To me the code should not even compile.


the code will compile because objects added are mutually comparable i.e they both are Test objects.
It would throw ClassCastException if you add a Test and say a Integer.
 
G Venu
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agreed. exception should be seen at runtime only

replacing with should fix the issue. (the code does not make much sense doing this though)
 
Phungsuk Wangdu
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks venu and neha you just cleared a lot of my doubts
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic