SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arraylists
Exercise:
Exercises
Question:19 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer




// 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]
0 0

Discussions

Post the discussion to improve the above solution.