Java OCA OCP Practice Question 2709

Question

What is the result of the following program?

import java.util.*; 

public class Main implements Comparable<Main>, Comparator<Main> { 
   private int num; 
   private String text; 

   Main(int n, String t) { 
      this.num = n; 
      this.text = t; 
   } /* w ww.j  a  v a2  s  .  c  o  m*/

   public String toString() { return "" + num; } 
   public int compareTo(Main s) { return text.compareTo(s.text); } 
   public int compare(Main s1, Main s2) { return s1.num - s2.num; } 
   
   public static void main(String[] args) { 
     Main s1 = new Main(88, "a"); 
     Main s2 = new Main(55, "b"); 
     TreeSet<Main> t1 = new TreeSet<>(); 
     t1.add(s1);   
     t1.add(s2); 
     TreeSet<Main> t2 = new TreeSet<>(s1); 
     t2.add(s1); 
     t2.add(s2); 
     System.out.println(t1 + " " + t2); 
   } 
} 
  • A. [55. 88] [55, 88]
  • B. [55. 88] [88, 55]
  • C. [88. 55] [55, 88]
  • D. [88. 55] [88, 55]
  • E. The code does not compile.
  • F. A runtime exception is thrown.


C.

Note

This question is hard because it defines both Comparable and Comparator on the same object.

t1 doesn't specify a Comparator so it uses the Comparable object's compareTo() method.

This sorts by the text instance variable.

t2 did specify a Comparator when calling the constructor, so it uses the compare() method, which sorts by the int.




PreviousNext

Related