Java OCA OCP Practice Question 1587

Question

What is the output of the following?

class Shape {
  private String name;
  public Shape(String name) {
     this.name = name;
  }//from ww w .  j  a  va2s.  c o  m
  public int compareTo(Shape m) {
     return name.compareTo(m.name);
  }
  public String toString() {
     return name;
  }
}
public class Main {
  public static void main(String[] args) {
     Set<Shape> set = new TreeSet<>();
     set.add(new Shape("A"));
     set.add(new Shape("B"));
     set.add(new Shape("A"));
     System.out.println(set.iterator().next());
  }
}
  • A. A
  • B. B
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


D.

Note

The Shape class doesn't implement Comparable<Shape>.

It happens to implement the compareTo() method properly, but it is missing actually writing implements Comparable.

Since TreeSet doesn't look to see if the object can be compared until runtime, this code throws a ClassCastException when TreeSet calls add(), so Option D is correct.




PreviousNext

Related