Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
可比Java排序_Java_Sorting_Comparable - Fatal编程技术网

可比Java排序

可比Java排序,java,sorting,comparable,Java,Sorting,Comparable,我搞不懂为什么输出是向后排序的:3,2,1。当这个.number>number时,我的compareTo方法返回一个正数,那么这不应该确保这些数字按顺序排序——从最小到最大吗? 谢谢您的比较中有一个错误方法总是返回-1。但是,您可以通过实现Comparable而不是Comparable来简化compareTo方法: public class person implements Comparable{ int number; public person(int number){

我搞不懂为什么输出是向后排序的:3,2,1。当这个.number>number时,我的compareTo方法返回一个正数,那么这不应该确保这些数字按顺序排序——从最小到最大吗?
谢谢

您的
比较中有一个错误
方法总是返回-1。但是,您可以通过实现
Comparable
而不是
Comparable
来简化
compareTo
方法:

public class person implements Comparable{
    int number;
    public person(int number){
        this.number = number;
    }
    public int compareTo(Object o){
        if(!(o instanceof person)){
            System.out.println("error");
            System.exit(1);
            person newObject = (person) o;
            if (this.number > newObject.number){
                return 1;
            }
            else if(this.number == newObject.number){
                return 0;
            }
        }
        return -1;
    }
}
class-Person实现可比性{
公共int比较(其他人){
返回this.number-other.number;
}
}

您只需将
compareTo
方法更改为以下内容,这样,如果传递的不是
person
的实例,它就可以返回错误,否则它将强制转换传递的对象并对其进行比较:

class Person implements Comparable<Person> {
    public int compareTo(Person other) {
        return this.number - other.number;
    }
}

如果我正确地阅读了
compareTo
中最外层的
If
语句,那么该方法似乎总是返回-1…Protip-
Comparable
将比这里的
Comparable
好得多哦,你是对的。谢谢那么-1和1实际上意味着什么呢。如何按照我想要的方式对事物进行排序。如文档所述:
负整数、零或正整数,因为此对象小于、等于或大于指定对象。
class Person implements Comparable<Person> {
    public int compareTo(Person other) {
        return this.number - other.number;
    }
}
 public int compareTo(Object o){
    if(!(o instanceof person)){
        System.out.println("error");
        System.exit(1);
    }

    person newObject = (person) o;
    if (this.number > newObject.number){
       return 1;
    }
    else if(this.number == newObject.number){
       return 0;
    }
    return -1;
}