sorting - java - compareTo method -


i have question compareto method in java. compareto method compares carowner objects , if calling object earlier in chronological time in comparison argument returns -1, if calling object later in chronological time in comparison argument returns 1, if calling object , argument same in chronological time returns 0. if argument passed in not carowner object (use instanceof or getclass determine this) or null, returns -1.

and came code, doesnt seem working, have 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; } 

should work, if getyear() , getmonth() returns 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() , 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; } 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -