我正在学习数组,基本上我有一个收集姓氏、名字和分数的数组。
我需要写一个compareTo
方法将比较姓氏和名字,以便列表可以从姓氏开始按字母顺序排序,然后如果两个人的姓氏相同,那么它将对名字进行排序。
我很困惑,因为我书中的所有信息都是比较数字,而不是对象和字符串。
这是我迄今为止编写的代码。我知道这是错误的,但它至少解释了我认为我在做什么:
public int compare(Object obj) // creating a method to compare
{
Student s = (Student) obj; // creating a student object
// I guess here I'm telling it to compare the last names?
int studentCompare = this.lastName.compareTo(s.getLastName());
if (studentCompare != 0)
return studentCompare;
else
{
if (this.getLastName() < s.getLastName())
return - 1;
if (this.getLastName() > s.getLastName())
return 1;
}
return 0;
}
我知道 <
和 >
符号是错误的,但就像我说的,我的书只向您展示了如何使用 compareTo
.
最佳答案
这是比较字符串的正确方法:
int studentCompare = this.lastName.compareTo(s.getLastName());
这甚至不会编译:
if (this.getLastName() < s.getLastName())
使用
if (this.getLastName().compareTo(s.getLastName()) < 0)
而是。
所以要比较您需要的拳头/姓氏顺序:
int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
d = getLastName().compareTo(s.getLastName());
return d;
关于java - 如何编写比较对象的 compareTo 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10017381/