aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inquisition Question 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 "Inquisition Question" Watch "Inquisition Question" New topic
Author

Inquisition Question

Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504


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.


SCJP 1.6 96%
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9302
    
  17

Hint: The class test implements Comparator and not Comparable...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
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

Joined: Mar 30, 2009
Posts: 5
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

Joined: Oct 30, 2009
Posts: 504
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

Joined: Mar 30, 2009
Posts: 5
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

Joined: Nov 04, 2009
Posts: 114
thanks venu and neha you just cleared a lot of my doubts
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inquisition Question