对子类与父类多种体,实现接口,并对其实现表面积排序

创建子类与父类,有球体,正方体,圆柱体,并求其体积和表面积,并让其实现Comparable接口,实现对表面积的排序;在测试类中创建数组,利用Arrays.sort或Collections.sort对该数组排序。

import java.util.Arrays;

abstract class Shape implements Comparable<Shape> {
    public abstract double getVolume();

    public abstract double getSurfaceArea();

    @Override
    public int compareTo(Shape o) {
        return Double.compare(getSurfaceArea(), o.getSurfaceArea());
    }
}

class Sphere extends Shape {
    private final double radius;

    Sphere(double radius) {
        this.radius = radius;
    }

    @Override
    public double getVolume() {
        return 4.0 / 3.0 * Math.PI * radius * radius * radius;
    }

    @Override
    public double getSurfaceArea() {
        return 4.0 * Math.PI * radius * radius;
    }
}

class Cube extends Shape {
    private final double side;

    Cube(double side) {
        this.side = side;
    }

    @Override
    public double getVolume() {
        return side * side * side;
    }

    @Override
    public double getSurfaceArea() {
        return 6.0 * side * side;
    }
}

class Cylinder extends Shape {
    private final double radius;

    private final double height;

    Cylinder(double radius, double height) {
        this.radius = radius;
        this.height = height;
    }

    @Override
    public double getVolume() {
        return Math.PI * radius * radius * height;
    }

    @Override
    public double getSurfaceArea() {
        return 2.0 * Math.PI * radius * (radius + height);
    }
}

class Shapes {
    public static void main(String[] args) {
        Shape[] shapes = {
            new Sphere(2.0),
            new Cube(3.0),
            new Cylinder(2.0, 4.0)
        };
        Arrays.sort(shapes);
        for (Shape shape : shapes) {
            System.out.println("表面积: " + shape.getSurfaceArea() + ", 体积: " + shape.getVolume());
        }
    }
}
  • 看下这篇博客,也许你就懂了,链接:【第42天】Arrays.sort 与 Collections.sort 应用 | 整形数组与集合的排序
  • 除此之外, 这篇博客: 如何使用Arrays.sort()对任意类型的数据进行排序?中的 5. 总结 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 从上面分析的内容中可以看出,如果对于除基本数据类型的数据使用Arrays.sort()ArrayList.sort()进行排序时,有两种使用方式:

    • 自定义类要实现Camparable接口,从重写其中的CompareTo(),重写的方法中定义自己的排序逻辑
    • 实现自定义的Comparator,并重写其中的Compare(),同样需要在重写方法中定义排序的规则,然后将其作为方法的参数传入

    另外,在代码实现中我们还随便复习了一下有关集合类的遍历的三种方法:

    • 使用for-each进行遍历

      for (Student student : s) {
          System.out.println(student);
      }
      
    • 使用Iterator进行遍历

      Iterator<String> iter = list.iterator();
      while (iter.hasNext()){
          System.out.println(iter.next());
      }
      
    • 使用forEach()进行遍历

      list.forEach(k-> System.out.println(k));