import java.util.*;
public class testPerson{
public static void main(String[] args){
person Albert = new person(1);
person James = new person(2);
person Elizabeth = new person(3);
person [] personArray = new person[3];
personArray[0] = Albert;
personArray[1] = James;
personArray[2] = Elizabeth;
Arrays.sort(personArray);
System.out.println(personArray[0].number);
System.out.println(personArray[1].number);
System.out.println(personArray[2].number);
}
}
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;
}
}
我很困惑为什么输出会向后排序:3,2,1。当this.number>数字时,我的compareTo方法返回一个正数,所以不应该确保数字按顺序排序 - 从最小到最大? 感谢
答案 0 :(得分:0)
compareTo
方法中的错误总是返回-1。不过,您可以通过实施compareTo
而不是Comparable<Person>
来简化Comparable
方法:
class Person implements Comparable<Person> {
public int compareTo(Person other) {
return this.number - other.number;
}
}
答案 1 :(得分:0)
您只需要将compareTo
方法更改为以下内容,因此如果传递的不是person
的实例,它可以返回错误,否则它将转换传递的对象并进行比较:
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;
}