-3

我的简单示例(编译的工作代码)只是不按重量对水果进行分类。

import java.util.Arrays;

public class Test {

    public static class Fruit implements Comparable<Fruit> {
        public int weight = 0;
        public Fruit(int w) { weight = w; }
        // compare this fruit to a given fruit f
        public int compareTo(Fruit f) {
            return (weight > f.weight) ? 1 : 0;
        }
    }

    public static void main(String[] args) {

        // get some fruits (we intentionally create a box for 100 fruits)
        Fruit[] fruits = new Fruit[100];
        for (int i = 0; i < 10; i++) {
            fruits[i] = new Fruit((int)(Math.random() * 50 + 1));
        }

        // sort fruits by weight
        Arrays.sort(fruits, 0, 10);

        // print fruit weights
        for (int i = 0; i < 10; i++) {
            System.out.print(fruits[i].weight + " ");
        }

    }

}

为什么会这样?

好吧,在我的问题(不是关于水果)中,我的对象永远不会成对相等,这就是为什么我认为一个对象比另一个对象更大或更小。那么当我知道 0(对象相等)永远不会发生时,我该如何处理这种情况呢?

4

5 回答 5

7

compareTo必须返回 3 个值之一:

  • >0--> 大于

  • 0--> 相等

  • <0--> 小于

您的compareTo方法只返回0or 1; 解决这个问题。

于 2013-05-27T15:41:19.260 回答
4

使用public static int compare(int x, int y)类中的方法java.lang.Integer(从 Java 7 开始)。

public int compareTo(Fruit f) {
    return Integer.compare(weight, f.weight);
}
于 2013-05-27T15:43:37.503 回答
3

如果weight从不否定,那么您可以尝试

return weight - f.weight; 

代替

return (weight > f.weight) ? 1 : 0;

从最低值到最高值排序。

于 2013-05-27T15:43:22.300 回答
2

最好的方法是使用 JDK 提供的方法来比较int值,这也使得代码在做什么一目了然

public int compareTo(Fruit f) {
    return Integer.compare(weight, f.weight);
}

在版本 7 java 之前,您有两种选择:

public int compareTo(Fruit f) {
    return weight - f.weight; // terse, but slightly obtuse
}

public int compareTo(Fruit f) {
    return new Integer(weight).compareTo(f.weight); // ugly, but supposedly clear
}

我更喜欢减法,因为一旦你理解了它,从那时起它就很清楚了。

于 2013-05-27T15:47:58.767 回答
0

你的compareTo方法应该返回 -1, 0, 1

LESSER = -1;
EQUAL = 0;
BIGGER = 1;
于 2013-05-27T15:41:08.983 回答