问题描述
在 java 中比较对象字符串属性的一种方法是实现可比较的接口。
public class Person implements Comparable<Person> {
private String surname;
private String firstname;
public Person(String surname,String firstname) {
this.surname = surname;
this.firstname = firstname;
}
@Override
public int compareto(Person person) {
int compareResult = this.surname.compareto(person.surname);
if (compareResult == 0)
return this.firstname.compareto(person.firstname);
return compareResult;
}
如果对象相等,则程序返回 0。 否则程序返回一个负整数
例如:
Person person1 = new Person("Joe","Rock");
Person person2 = new Person("Joe","Stone");
person1.compareto(person2)
返回:-17
负整数背后的原因是什么?
注意:如果对象中的字符串发生变化且不相等,则负数将与现在不同。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)