kevinw
kevinw

Reputation: 1

compareTo on int types

I'm trying to compare a studentNumber with each other. but I cant figuur out how to do that with 2 int types. So when you add a student to your website you can't add the student with the same studentNbr.

I tried to make it into a string but that didn't help.

public int compareTo(Student o) {
    if (!(this.getStudentNbr() == (o.getStudentNbr()))) {
        return this.getStudentNbr().compareToIgnoreCase(o.getStudentNbr());
        }
    if (!this.getLastName().equals(o.getLastName())) {
        return this.getLastName().compareToIgnoreCase(o.getLastName());
    }
    if (!this.getFirstName().equals(o.getFirstName())) {
        return this.getFirstName().compareToIgnoreCase(o.getFirstName());
    }

    if (o.getInsertion() != null && this.getInsertion() != null) {
        if (!this.getInsertion().equals(o.getInsertion())) {
            return this.getInsertion().compareToIgnoreCase(o.getInsertion());
        }

    } else if (this.getInsertion() == null && o.getInsertion() != null) {
        if (!getInsertion().equals(o.getInsertion())) {
            return getInsertion().compareToIgnoreCase(o.getInsertion());
        }
    }
    return 0;
}

When I try this code you can just add students with the same studentNbr, and thats not good.

Have someone any idea how I can compare on two int types?

Upvotes: 0

Views: 83

Answers (2)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

You could use methods like Integer.compare(x, y) to compare values return if res is not equal to 0:

public class Student implements Comparable<Student> {

    private int studentNbr;
    private String lastName;
    private String firstName;
    //...

    @Override
    public int compareTo(Student student) {
        int res = Integer.compare(studentNbr, student.studentNbr);
        res = res == 0 ? lastName.compareToIgnoreCase(student.lastName) : res;
        res = res == 0 ? firstName.compareToIgnoreCase(student.firstName) : res;
        // ...

        return res;
    }
}

Upvotes: 1

bassner
bassner

Reputation: 53

To be honest, I don't exactly get your code, because if you just want to compare two students based on their studentNbr, just do

public int compareTo(Student o) {
    Integer.compare(getStudentNbr(), o.getStudentNbr());
}

Upvotes: 0

Related Questions