Modify the CalendarDate class from this chapter to include a year field, and modify its compareTo method to take years into account when making comparisons. Years take precedence over months, which take precedence over
days. For example, July 18, 1995 comes before March 2, 2001.
// CalendarDate.java (modified CalendarDate class)
public class CalendarDate implements Comparable
{
// refer the textbook for the CalendarDate class
private int month;
private int day;
private int year; // newly added variable
// modified constructor
public CalendarDate(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year = year;
}
// modified method
public int compareTo(CalendarDate other)
{
if(year != other.year)
{
return year - other.year;
}
if(month != other.month)
{
return month - other.month;
}
else
{
return day - other.day;
}
}
// newly added method
public int getYear()
{
return year;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
// modified method
public String toString()
{
return month + "/" + day + "/" + year;
}
}
// CalendarDateDemo.java
import java.util.ArrayList;
import java.util.Collections;
public class CalendarDateDemo
{
public static void main(String[] args)
{
CalendarDate cd1 = new CalendarDate(2, 2, 2001);
CalendarDate cd2 = new CalendarDate(7, 18, 1995);
CalendarDate cd3 = new CalendarDate(1, 30, 1995);
CalendarDate cd4 = new CalendarDate(2, 1, 2001);
ArrayList calendarDates = new ArrayList();
calendarDates.add(cd1);
calendarDates.add(cd2);
calendarDates.add(cd3);
calendarDates.add(cd4);
System.out.println("Calendar dates in the list before soring: "
+ calendarDates);
Collections.sort(calendarDates);
System.out.println("Calendar dates in the list after soring: "
+ calendarDates);
}
}
Output :
Calendar dates in the list before soring: [2/2/2001, 7/18/1995, 1/30/1995, 2/1/2001]
Calendar dates in the list after soring: [1/30/1995, 7/18/1995, 2/1/2001, 2/2/2001]