关于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;
}发布于 2014-12-06 04:39:31
如果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;
}发布于 2014-12-06 04:41:04
您正在将此实例的属性与整个otherOwner实例进行比较。您应该与otherOwner的属性进行比较。
例如
otherOwner.getYear().compareTo(getYear())
发布于 2014-12-06 04:40:51
如果将该方法应用于某些CarOwner,则会发生以下情况:
所以,你应该做的是将“年份”或“月份”与其他所有者的“年份”或“月份”进行比较,并返回结果。
https://stackoverflow.com/questions/27328344
复制相似问题