简体   繁体   English

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

[英]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;
    }
}
}

Don't make things more complicated: 不要让事情变得更复杂:

  • String class already provides compareToIgnoreCase method String类已经提供了compareToIgnoreCase方法
  • value returned by compare methods of String is already good to be directly returned String的compare方法返回的值已经很好,可以直接返回

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. 请注意,如果您有Object参数,则需要检查o instanceof Student

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 ). 我不明白为什么要使用自定义的IComparable接口,这听起来很像C#中提供的接口,因为Java提供了Comparable<T> ,它是通用的,不需要检查参数的运行时类型(因为它是不再是Object ,而是T )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM