JAVA如何在本练习中使用compareTo比较整数

时间:2015-02-07 10:02:25

标签: java compareto

我正在尝试做这个练习:我有一个学生,有一个姓名和一个号码,我想按编号订购学生..如果我想通过姓名或姓氏订购,这似乎很容易,但是号码我不知道怎么办.. 这是我的代码:

public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;


public Student(String n, String s, int m) {
    name = n;
    surname = s;
    number = m;
}

public String getName() {
    return name;
}

public String getSurname() {
    return surname;
}

public int getmatricola() {
    return number;
}
//CompareTo Name
public int compareTo(Student otherObject) {
    return name.compareTo(otherObject.getName());
}
}
//TESTER
 ArrayList<Student> list = new ArrayList<Student>(); 
 System.out.print("\n ORDER BY NUMBER \n");

    Collections.sort(list);
    for (int i = 0; i < list.size(); i++) {
        Student s = list.get(i);
        String std = s.getAll();
        System.out.println(std);


    }

3 个答案:

答案 0 :(得分:1)

您可以实现以下内容:

public int compareTo(Student otherObject) {
    return Integer.compare(this.number, otherObject.getNumber());
}

答案 1 :(得分:0)

那么为什么你的数字是一个int你可以减去数字并返回差异:

public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;


public Student(String n, String s, int m) {
    name = n;
    surname = s;
    number = m;
}

public String getName() {
    return name;
}

public String getSurname() {
    return surname;
}

public int getmatricola() {
    return number;
}
//CompareTo number
public int compareTo(Student otherObject) {
    return number - otherObject.getmatricola();
}
}

答案 2 :(得分:0)

尝试这样做......应该有效         // CompareTo名称         public int compareTo(Student otherObject){           if(this.getmatricola()&gt; otherObject.getmatricola())                                 返回1;           其他                 返回-1;         }