GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes comparator comparable 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 "comparator comparable" Watch "comparator comparable" New topic
Author

comparator comparable

Ganesh Pujar
Ranch Hand

Joined: Mar 22, 2006
Posts: 45
<Code>
import java.util.*;
class test implements Comparator < test >
{
int testNumber;
public static void main( String args[] )
{
Set < test > s1 = new TreeSet < test > ();

s1.add(new test());
s1.add(new test());

}
public int compare( test t1 , test t2 )
{
return t1.testNumber - t2.testNumber;
}

}


Choose 3 that apply.

a.Compiles without warnings
b.Compiles with warnings
c.Only one test Object is added, the other one is considered a duplicate.
d.A Runtime Exception occurs.
e.TreeSet can only accept objects of type test. ( Given that test has no sub classes )

</Code>
Answer is
Answer: a d e : test needs to implement Comparable rather than Comparator to be able to sort its objects automatically. A RuntimeClassCastException is thrown.
Please explane me HOW?
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023

Answer: a d e : test needs to implement Comparable rather than Comparator to be able to sort its objects automatically. A RuntimeClassCastException is thrown.
Please explane me HOW?



TreeSet API:
public TreeSet()Constructs a new, empty set, sorted according to the elements' natural order. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add(Object) call will throw a ClassCastException.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: comparator comparable