CompareTo(Object o)用于比较java中的字符串

0 java string object compareto

在我的程序中,我试图按姓氏比较名称,如果它们相同,则使用名字进行比较.但是,我无法弄清楚如何比较字符串.

有人可以帮我解决这个问题吗?

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;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*ack 5

不要让事情变得更复杂:

  • Stringclass已经提供了compareToIgnoreCase方法
  • 比较方法返回的值String已经很好,可以直接返回

基本上相同的功能可以表示为:

int compare = getLastName().compareToIgnoreCase(o.getLastName());
return compare == 0 ? getFirstName().compareToIgnoreCase(o.getFirstName()) : compare;
Run Code Online (Sandbox Code Playgroud)

请注意,o instanceof Student如果你有Object争论,你需要检查一下.

我不明白为什么你使用自定义IComparable界面,这听起来很像C#中提供的界面,因为Java提供了Comparable<T>通用的,并且不需要检查参数的运行时类型(因为它Object不再是T).