Discuss / Java / 用score进行排序

用score进行排序

Topic source

由于基本类型int并不能使用compareTo函数,因此在定义score时将int改为Integer:

class Person implements Comparable<Person>{    String name;    Integer score;    Person(String name, int score){        this.name = name;        this.score = score;    }    public int compareTo(Person other){        return this.score.compareTo(other.score);    }    public String toString(){        return this.name +","+this.score;    }}

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

你这是学糊涂了,两个int比较:

this.score==other.score

Andylbc

#3 Created at ... [Delete] [Delete and Lock User]

return this.score - other.score;

哈哈哈哈哈,我也是学糊涂了,一个劲儿的调用compaerTo方法去比较两个int类型的大小,结果编译报错,int类型是基本类型,直接比较就是了,不用调那个方法,廖老师点拨的很及时

string 为什么 可以 直接调用 因为 本身重写了 compaerTo方法

当前 integer 也重写了 你定义integer 直接调用 compaerTo方法 我觉得 也没啥问题

Joker.fu_95

#6 Created at ... [Delete] [Delete and Lock User]

是没啥问题,只是多此一举


  • 1

Reply