为什么实现Comparable的对象不是排序的?

Sop*_*ner -3 java sorting

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

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 + " ");
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

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

SJu*_*n76 7

compareTo 必须返回3个值中的一个:

  • >0 - >大于

  • 0 - >平等

  • <0 - >不到

你的compareTo方法只返回01; 修复它.

  • = 1不正确.`compareTo()`可以返回任何`int`值. (3认同)