尝试使用 JAVA 中可比较的接口对数组进行排序

Trying to sort array using the interface comparable in JAVA

我有一个摘要 class 和几个子 class 以及一个主要 class 我有形状数组,并尝试使用可比较的

按面积降序对数组进行排序

目前为止我有一个可比较的代码,但它不会排序也不会打印。

形状摘要 CLASS

import java.text.*;
public abstract class shape implements Comparable<shape> {

    private int id;
    private String label; 
    private static int counter = 1; // to keep count and unique over all classes 
    private static DecimalFormat df2 = new DecimalFormat("#.##");
    public shape(String label) {
        this.id = counter;
        counter ++ ;   //this is counter for unique id can also have a default constructor seperate for count 
        this.label = label;
    }

    public int getId() {
        return id;
    }

    public String getLabel() {
        return label;
    }

    public interface Comparable {
        public int compareTo(shape o);
    }

     public int compareTo(shape o) {
        if (this.CalcArea() > o.CalcArea())
            return 1;
        else if (this.CalcArea() < o.CalcArea())
            return -1;
        else 
            return 0;
    }
    //to calculate area= abstract method
    public abstract double CalcArea(); // this is the prototype and has to be used once in derived classes

    public String toString() {

        //df2.format(CalcArea())
        return "ID " + this.id + ": the shape is " + label + " and the area calculated is "+  
                df2.format(CalcArea());
    }

}

// 主驱动程序 CLASS

import java.util.*;
public class DrawingApp {

    /*public DrawingApp() {

    }*/


    public static void main(String[] args) {



        int shapeType;
        int i; //two for loops so better here
        //next gaussian if using double
        shape[] shaper = new shape[10]; //instantiating array object not the shape
        Random num = new Random();
        Random num1 = new Random();  //*100 + 1 
        for ( i = 0; i < 10 ; i++) {
            shapeType = num.nextInt()% 2 ;
            if(shapeType == 0 ) {
                shaper[i] = new circle((num1.nextDouble()*9)+1); //can use random as the shapes are created randomly and array of ten
            }else if(shapeType == 1) {
                shaper[i] = new Rectangle((num1.nextDouble()*9)+1,(num1.nextDouble()*9)+1); 
            }else {
                shaper[i] = new Triangle((num1.nextDouble()*9)+1,(num1.nextDouble()*9)+1);
            }
        }
        for ( i = 0; i < 10 ; i ++) {
            shaper[i].CalcArea();
        }

        for(shape s : shaper){

            System.out.println(s);
        }
    }

}

考虑到您的圆形、矩形和三角形 类 已正确实现,请添加行 Arrays.sort(shaper); 以对数组进行排序。它将使用您的形状的 compareTo 方法按面积对形状进行排序。照原样,我没有看到任何排序尝试。

您调用 CalcArea() 方法的 for 循环似乎也什么都不做,因为您从不使用 return 值。