ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Shape implements Comparable<Shape> {
    double area;
    Shape(double a) { area = a; }
    public int compareTo(Shape o) { return Double.compare(area, o.area); }
    public String toString() { return String.valueOf(area); }
}
// in main:
List<Shape> shapes = new ArrayList<>(List.of(new Shape(5), new Shape(2), new Shape(8)));
Collections.sort(shapes);
System.out.println(shapes);
  1. A. [2.0, 5.0, 8.0]
  2. B. [5.0, 2.0, 8.0]
  3. C. [8.0, 5.0, 2.0]
  4. D. Compilation error: Shape must override equals() to implement Comparable

Correct answer: A. [2.0, 5.0, 8.0]

Shape implements Comparable<Shape>, providing a natural ordering by area; Collections.sort uses compareTo() to sort ascending, giving [2.0, 5.0, 8.0]. Comparable requires no equals() override — that's a separate, unrelated contract.

More OOP with C++ and Java questions

Exams that ask this topic