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);- A. [2.0, 5.0, 8.0]
- B. [5.0, 2.0, 8.0]
- C. [8.0, 5.0, 2.0]
- 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
- What is printed? java class Base { public Object process() { return "base-result"; } } class Derived extends Base { @Override public…
- What is printed? cpp class Logger { public: static Logger& instance() { static Logger inst; return inst; } void log(const string& msg) {…
- What is printed? java class EventBus { private static EventBus instance; private EventBus() { System.out.print("created "); } public…
- What is printed? java class Base { Base clone2() { return new Base(); } } class Derived extends Base { @Override Derived clone2() { return…
- What is printed? java class Animal { void makeSound() { System.out.print("..."); } } class Dog extends Animal { @Override void makeSound()…
- What is printed? java class Base { Base() { System.out.print("Base "); } } class Mid extends Base { Mid() { System.out.print("Mid "); } }…