• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

comparator comparable

 
Ganesh Pujar
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<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
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic