可比Java排序
我搞不懂为什么输出是向后排序的:3,2,1。当这个.number>number时,我的compareTo方法返回一个正数,那么这不应该确保这些数字按顺序排序——从最小到最大吗?可比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){
谢谢您的
比较中有一个错误
方法总是返回-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;
}