排序方法是正确的..但是没有排序成功...求指点~~~~

public class Testshape{
public static void main(String[] args){
Shape[] c = new Circle[5];
int i;
for( i=0; i<c.length; i++)
c[i] = new Circle(i);
for( i=0; i<c.length; i++)
System.out.println(c[i].toString());
Sort(c);//执行排序方法后...结果没变
for( i=0; i<c.length; i++)
System.out.println(c[i].toString());
}
public static void Sort(Shape[] list){
Shape currentMax;
int currentMaxIndex;

for(int i = list.length - 1;i >= 0;i--){

currentMax = list[i];

currentMaxIndex = i;

for(int j = i ;j >=0;j--){

if(list[i].getArea()<list[j].getArea()){

currentMax = list[j];

currentMaxIndex = j;

}

}//System.out.println(currentMax.toString());

if(currentMaxIndex != i){

list[currentMaxIndex] = list[i];

list[i] = currentMax;

}

}

}
}




class Shape{
protected double compareTo(Shape s){return 0;}
protected double getPerimeter(){return 0;}
protected double getArea(){return 0;}
public double getRadius(){return 0;}
public void setRadius(double r){}
}   
class Circle extends Shape{
private double radius;
public Circle(){}
public Circle(double r){radius = r;}
public double getRadius(){return radius;}
public void setRadius(double r){radius = r;}
public String toString()
{
System.out.println( "[Circle]radius = "+radius);return "";
}
public double getPerimeter(){return 2*3.1415*radius;}
public double Area(){return 3.1415*radius*radius;}
}
/*class Rectangle extends Shape{
private double length;
private double width;
public Rectangle(double l,double w){length = l;width = w;}
public double getLength(){return length;}
public void setLength(double l){length = l;}
public double getWidth(){return width;}
public void setWidth(double w){width = w;}
public String toString()
{
System.out.println("[Rectangle]length = "+length+"and width = "+width);return "";
}
public double getPerimeter(){return 2*(length+width);}
public double getArea(){return length*width;}
}
*/

1个回答

//用数组没问题的,看了一下你的程序,发现很多问题
//首先,Circle的toString有问题
public String toString()
{
//System.out.println( "[Circle]radius = "+radius);return ""; //打印是打印了,但是正确的信息没返回
    return String.format("[Circle]radius = %.2f", radius);
}
其次Circle的getArea方法没有重写
public double Area(){return 3.1415*radius*radius;} //方法名和父类方法名不一样,而实际比较调用的时候是调用getArea,所以返回的是父类的getArea的返回值0,所以比较没有意义,导致没有发生排序


//另,1L的排序方法有个地方失误了
public static void Sort(Shape[] list){
    for(int i=0; i<list.length; i++){
        for(int j=1 ;j<list.length-i; j++){//之前这里笔误为j=i+1了
            if(list[j].getArea()<list[j-1].getArea()){
                Shape tmp = list[j];
                list[j] = list[j-1];
                list[j-1] = tmp;
            }
       }
    }
}