Jordan Dent
Jordan Dent

Reputation: 13

CompareTo(Object o) used to compare strings in java

In my program I'm trying to compare names by last name, and if those are the same then compare by using the first name. However, I can't quite figure out how to compare the strings.

Can someone help me out with this?

public class Student implements IComparable
{
String firstName;
String lastName;
int score;

public Student()
{

}

public void setFirstName(String firstName)
{
    this.firstName = firstName;
}
public String getFirstName()
{
    return firstName;
}

public void getLastName(String lastName)
{
    this.lastName = lastName;
}
public String getLastName()
{
    return lastName;
}

public void getScore(int score)
{
    this.score = score;
}
public int getScore()
{
    return score;
}

@Override
public int compareTo(Object o)
{
   //Compares Student objects by last name. If the last names are the same 
   //it compares by first name.
    Student s = (Student) o;

    if (this.getLastName().toUpperCase() < s.getLastName().toUpperCase())
        return -1;
    else if (this.getLastName().toUpperCase() > s.getLastName().toUpperCase())
        return 1;
    else
    {
        if(this.getFirstName().toUpperCase( < s.getFirstName().toUpperCase()
            return -1;
        else if (this.getFirstName().toUpperCase( > s.getFirstName().toUpperCase()
            return 1;
        else
            return 0;
    }
}
}

Upvotes: 0

Views: 1361

Answers (1)

Jack
Jack

Reputation: 133609

Don't make things more complicated:

  • String class already provides compareToIgnoreCase method
  • value returned by compare methods of String is already good to be directly returned

Basically the same functionality could be expressed with:

int compare = getLastName().compareToIgnoreCase(o.getLastName());
return compare == 0 ? getFirstName().compareToIgnoreCase(o.getFirstName()) : compare;

Mind that you need to check that o instanceof Student if you have an Object argument.

I don't get why you are using a custom IComparable interface, which sounds much like the one provided in C#, since Java provides Comparable<T> which is generic and doesn't require checking for the runtime type of the argument (since it's not Object anymore but T).

Upvotes: 5

Related Questions