【发布时间】:2019-02-02 00:39:25
【问题描述】:
我的 Java 程序没有对输出进行排序。我没有使用 Java 的经验,在查看了类似的问题后,我无法找出我的代码存在的问题。
输出显示 3 个球体及其颜色,但不显示半径或按其区域排序。
以下是我的程序中涉及的 3 个 .java 文件,我在 Eclipse 中没有错误或警告,所以我假设我将一些参数或值放在了错误的位置...非常感谢任何帮助!
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);
}
}
【问题讨论】:
-
你好像没有写
compareTo方法。当您的程序无法比较两个对象时,您希望如何对对象进行排序? -
public int compareTo(ComparableSphere o) { return 0; }表示所有对象都比较 相等 (因为这就是返回值 0 的意思),如果它们都相等,你为什么会期望sort()什么都做? --- 实现compareTo方法。 -
写在哪里? compareTo 方法在 ComparableSphere.java 中,是否也需要在 driver.java 中?
标签: java arrays collections compareto