Reputation: 67
i have a question about compareTo method in java. So this compareTo method compares CarOwner objects and if the calling object is earlier in chronological time in comparison to the argument returns -1, if the calling object is later in chronological time in comparison to the argument returns 1, if the calling object and argument are the same in chronological time returns 0. if the argument passed in is not a CarOwner object (use instanceof or getClass to determine this) or is null, returns -1.
and i came up with this code, but it doesnt seem like its working, anybody have any suggestion?
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;
}
Upvotes: 0
Views: 1704
Reputation: 2149
Should work, if getYear() and getMonth() returns the comparable objects
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;
}
if getYear() and getMonth() returns int, then:
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;
}
Upvotes: 0
Reputation: 7890
Implement the Compareable interface on your class (Comparable<CarOwner>
) after that use CarOwner for your compareTo method instead of Object (int compareTo(CarOwner otherOwner)
)
Upvotes: 0
Reputation: 394106
You are comparing properties of this instance to the entire otherOwner instance. You should compare to properies of otherOwner.
For example
otherOwner.getYear().compareTo(getYear())
Upvotes: 1
Reputation: 1029
As you are comparing different fields and digging deeper if year field is the same, I suggest the following
int oy=otherOwner.getYear();
int ty=this.getYear();
int om=otherOwner.getMonth();
int tm=this.getMonth();
if(oy==ty){
return om-tm;
}else{
return oy-ty;
}
Upvotes: 0
Reputation: 1032
If you apply the method to some CarOwner, what will happen is:
So what you should do is compare "Year" or "Month" with otherOwner's "Year" or "Month" and return the result.
Upvotes: 0