collections.sort不排序,仅使输出不排序

时间:2019-02-02 00:39:26

标签: java arrays collections compareto

我的Java程序未对输出进行排序。我没有Java的经验,在浏览了类似的问题之后,我无法找出我的代码存在的问题。

输出显示3个球体及其颜色,但不显示半径或按其区域对它们进行排序。

下面是我的程序中涉及的3个.java文件,我在Eclipse中没有错误或警告,所以我假设我将一些参数或值放在错误的位置...非常感谢您的帮助! / p>

ComparableSphere.java

public class ComparableSphere extends GeometricObject implements Comparable<ComparableSphere>{

private double radius;

public ComparableSphere(){
    this("white",0);
    this.radius = 0;
}
public ComparableSphere(String color, double radius){
    super(color);
    this.radius = radius;
}
public double area() {
    return Math.PI * this.radius * this.radius * 4;
}
public double perimeter() {
    return 2 * Math.PI * this.radius;
}

@Override
public int compareTo(ComparableSphere o) {
    // TODO Auto-generated method stub
    return 0;
}

}

GeometricObject.java

public abstract class GeometricObject {

private String color;


protected GeometricObject(){
    this("white");
}


protected GeometricObject(String color) {
    this.color = color;
}


public String getColor(){
    return this.color;
}


public void setColor(String color){
    this.color = color;
}


public abstract double area();


public abstract double perimeter();


public String toString() {
    return this.getClass().getSimpleName() + ": color= " + this.color;
}



public boolean equals(Object obj) {
    if(!(obj instanceof GeometricObject)){
        return false;
    }

    GeometricObject other = (GeometricObject)obj;
    return this.color.equalsIgnoreCase(other.color);
}

}

driver.java

import java.util.ArrayList;
import java.util.Collections;

public class driver {
    public static void main(String[] args){
        ComparableSphere sphere1 = new ComparableSphere("Purple", 10.1);
        ComparableSphere sphere2 = new ComparableSphere("Orange", 3.8);
        ComparableSphere sphere3 = new ComparableSphere("Tan", 5.2);

        ArrayList<ComparableSphere> sphereList = new ArrayList<ComparableSphere>();

        sphereList.add(sphere1);
        sphereList.add(sphere2);
        sphereList.add(sphere3);

        System.out.println("Unsorted list: \n"+sphereList+"\n");

        Collections.sort(sphereList);
        System.out.println("Sorted list: \n"+sphereList);

}

}

enter image description here

1 个答案:

答案 0 :(得分:0)

根据the compareTo contract,您的CASE WHEN EXISTS(...) THEN 1 ELSE 0 END总是返回compareTo,这意味着您正在考虑所有0个对象彼此相等:

  

将此对象与指定对象进行比较。当此对象小于,等于或大于指定的对象时,返回负整数,零或正整数。

这意味着ComparableSphere认为它无关紧要,因为所有对象彼此相等。

您需要在Collections.sort方法中编写逻辑,以便在此对象与传入的对象之间进行比较并返回适当的值。这将为compareTo提供正确排序列表所需的信息。