Java compareTo method beginner level

sort the students based on the neptun code

Two parts. Part one, change

implements Comparable

to

implements Comparable<Student>

And then

@Override
public int compareTo(Student o) {
    return this.nep_c.compareTo(o.nep_c);
}

However, you then say Within it, by the number of mark you get. so perhaps you really want

@Override
public int compareTo(Student o) {
    return Integer.compare(getMark(), o.getMark());
}

If you mean to sort by neptun code, and use mark(s) as a tie-breaker then you could do something like

int c = this.nep_c.compareTo(o.nep_c);
if (c != 0) {
    return c;
}
return Integer.compare(getMark(), o.getMark());

Or, in Java 8+, using Comparator.comparing like

return Comparator.comparing(Student::getNep_c)
        .thenComparingInt(Student::getMark).compare(this, o);

compareTo gets Object because you implement Comparable, rather than generic Comparable<Student>. That is why it is hard to see what needs to be done.

Change your code as follows:

public class Student implements Comparable<Student> {
    ...
    @Override
    public int compareTo(Student other) {
        ...
    }
}

Now inside the implementation compare nep_c of this student to other.nep_c. If these two are not equal, return the result of comparison; otherwise return the result of comparing the marks.

Note: There is an issue with your getMark method: it returns 1 for students with 60 points when it should return 2, and it also assigns private Mark field which could be converted to a local variable.


The compareTo method on a Comparable takes a value to which it compares the current object, and should return:

  • -1 if the current object comes before the other object (any negative integer can be used),
  • 0 if the two objects are equal,
  • 1 if the current object comes after the other object (any positive integer can be used).

If you want to compare two objects by two different fields, you would do the following (make sure to implement Comparable<Student>):

@Override
public int compareTo(Student other) {
    final int comparedNepCode = nep_c.compareTo(other.nep_c);
    if (comparedNepCode == 0) {
        return Integer.compare(getMark(), other.getMark());
    }
    return comparedNepCode;
}

When comparing numbers, subtracting the other from the current one gives an ascending order, so:

  • x < y <=> x - y < 0
  • x = y <=> x - y = 0
  • x > y <=> x - y > 0