2

Learning java and having trouble with the compareTo method. I tried google but it was not much help for what i need.What i need is

// compareTo public int compareTo(Student other) 
// is defined in the Comparable Interface
    // and should compare the student ID's  (they are positive integers).
// Must be able to handle null "other" students. A null student should be
// ordered before any student s so the s.compareTo(null) should be positive.

so basically a compareTo(), in the end this method is going to help me put my students in order based on there student ids lowest to greatest.. I'm at a brick wall and just need some help in the right direction

public int compareTo(StudentIF other) {
    // do stuff
    return 0;
}
dave
  • 71
  • 1
  • 8

2 Answers2

3

There's a good tutorial about implementing compareTo() here. That said, when learning how to do something in general it's often helpful for me to see how to implement it in my specific use case - so, in this case, I would imagine something like this would suffice:

public int compareTo(StudentIF other) {
    if (other == null) {return 1;} //satisfies your null student requirement
    return this.studentId > other.studentId ? 1 : 
                            this.studentId < other.studentId ? -1 : 0;
}

compareTo() is expected to return a positive value if the other object is comparitively smaller, a negative value if it's comparitively larger, and 0 if they are equal. Assuming you're familiar with the ternary operator, you'll see that that's what this is doing. If you're not, then the if/else equivalent would be:

    public int compareTo(StudentIF other) {
        if (other == null) { return 1; } //satisfies your null student requirement
        if (this.studentId > other.studentId) return 1; 
        else if (this.studentId < other.studentId) return -1; 
        else return 0; //if it's neither smaller nor larger, it must be equal
}
drew moore
  • 31,565
  • 17
  • 75
  • 112
  • Very good explantion, and this all makes sense but what is getting me is my null case. I don't know what is suppose to happen with that. – dave Jul 29 '14 at 02:38
1

As the compareTo interface required:

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

plus your additional requirement of null comparison, we can simply check whether the other param is null or not, and then do a subtraction to compare.

public int compareTo(StudentIF other) {
    if (other == null) {
        return 1;
    }
    return this.id - other.id;
}
xi.lin
  • 3,326
  • 2
  • 31
  • 57