Untitled
unknown
plain_text
6 months ago
1.8 kB
2
Indexable
import java.util.Arrays; interface Sortable extends Comparable<Sortable>{ double getArea(); int compareTo(Sortable other); } class Circle3 implements Sortable { private double radius; public Circle3(double radius) { this.radius = radius; } @Override public double getArea() { return Math.PI * radius * radius; } @Override public int compareTo(Sortable other) { double otherArea = other.getArea(); return Double.compare(this.getArea(), otherArea); } } class Rectangle3 implements Sortable { private double width; private double height; public Rectangle3(double width, double height) { this.width = width; this.height = height; } @Override public double getArea() { return width * height; } @Override public int compareTo(Sortable other) { double otherArea = other.getArea(); return Double.compare(this.getArea(), otherArea); } } public class ShapeSortingExample { public static void main(String[] args) { Sortable[] shapes = { new Circle3(3.0), new Rectangle3(2.0, 4.0), new Circle3(2.5), new Rectangle3(3.0, 2.0), new Circle3(4.0) }; // Sort the shapes based on their areas Arrays.sort(shapes); // Display the sorted shapes for (Sortable shape : shapes) { if (shape instanceof Circle3) { System.out.printf("Circle - Area: %.2f%n", shape.getArea()); } else if (shape instanceof Rectangle3) { System.out.printf("Rectangle - Area: %.2f%n", shape.getArea()); } } } }
Editor is loading...
Leave a Comment