java - How to write a Comparator -
public class date { private int month; // must 1-12 private int day; // must 1-31 public int getmonth() {return month;} public int getday() {return day;} public date(int m, int d) { if (m >= 1 && m <= 12) month = m; else month = 1; if (d >= 1 && d <= 31) day = d; else day = 1; } // end constructor } // end class date
comparator class
import java.util.*; public class datecomparator implements comparator <date>{ public int compare(date date1, date date2){ if (date1.getmonth() > date2.getmonth()){ return 1; } else if(date1.getmonth() < date2.getmonth()){ return -1; } else{ //if(date1.getmonth() == date2.getmonth()){ if (date1.getday() > date2.getday()){ return 1; } if (date2.getday() < date2.getday()){ return -1; } else{// (date2.getday() == date2.getmonth()){ return 0; } } } }
i'm trying write comparator date class, , wondering if correct way it. advice appreciated!
first of all, question seems more appropriate code review. there concepts explain go beyond code review, decided post answer.
first draft
your comparator can considered first draft. working , compares 2 date
objects specified. done.
code improvement
the many if-else-statements make comparator clumsy , unreadable. keep in mind compare method not bound returning -1, 0, or 1. can return negative number if first argument less second one, , positive number if first argument greater second one. 0 return bound equality.
as month , day both represented integers, can use them in little arithmetic. month difference more important - weighs more - must heavier:
public int compare(date date1, date date2) { int monthdiff = date1.getmonth() - date2.getmonth(); int daydiff = date1.getday() - date2.getday(); return monthdiff * 100 + daydiff; }
subtractions produce negative number, zero, or positive number. use them. factor 100 makes month difference more important day difference.
if month difference not 0, adding day difference not have effect (because of factor 100). when month difference 0, day difference important.
code structure
comparing 2 dates way looks natural. in fact, natural ordering on dates. if type has such natural ordering, should (must) let implement comparable
:
public class date implements comparable<date> { ... @override public int compareto(date other) { int monthdiff = this.getmonth() - other.getmonth(); int daydiff = this.getday() - other.getday(); return monthdiff * 100 + daydiff; } }
other comparators
if feel must have other comparators, can add them. place nested static class inside date
class (as belong it).
let's make comparator take month account:
public class date implements comparable<date> { ... public static final class monthcomparator implements comparator<date> { @override public int compare(date date1, date date2) { return date1.getmonth() - date2.getmonth(); } } }
Comments
Post a Comment