我对Java中的compareTo方法有疑问。因此,此compareTo方法比较CarOwner对象,如果调用对象在时间上比参数返回的时间早,则返回-1,如果调用对象在时间上比参数返回的时间晚,则返回1,如果调用对象和参数是按时间顺序相同将返回0。如果传入的参数不是CarOwner对象(使用instanceof或getClass确定),则为null,则返回-1。
我想出了这段代码,但是看起来好像没有用,有人有什么建议吗?
public int compareTo(Object o)
{
if ((o != null ) && (o instanceof CarOwner))
{
CarOwner otherOwner = (CarOwner) o;
if (otherOwner.compareTo(getYear()) > 0)
return -1;
else if (otherOwner.compareTo(getYear()) < 0)
return 1;
else if (otherOwner.equals(getYear()))
if (otherOwner.compareTo(getMonth()) > 0)
return -1;
else if (otherOwner.compareTo(getMonth()) < 0)
return 1;
else if (otherOwner.equals(getMonth()))
return 0;
}
return -1;
}
最佳答案
如果getYear()和getMonth()返回可比较的对象,则应该工作
public int compareTo(Object o)
{
if ((o != null ) && (o instanceof CarOwner))
{
CarOwner otherOwner = (CarOwner) o;
int result = otherOwner.getYear().compareTo(getYear());
if (result != 0)
return result;
return otherOwner.getMonth().compareTo(getMonth());
}
return -1;
}
如果getYear()和getMonth()返回int,则:
public int compareTo(Object o)
{
if ((o != null ) && (o instanceof CarOwner))
{
CarOwner otherOwner = (CarOwner) o;
if (otherOwner.getYear() > getYear())
return -1
else if (otherOwner.getYear() < getYear())
return 1
else if (otherOwner.getMonth() > getMonth())
return -1
else if (otherOwner.getMonth() < getMonth())
return 1;
else
return 0;
}
return -1;
}