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:18 | ISBN:9780136091813 | Edition: 2

Question

Modify the TimeSpan class from Chapter 8 to include a compareTo method that compares time spans by their length. A time span that represents a shorter amount of time is considered to be “less than” one that represents a longer amount of time. For example, a span of 3 hours and 15 minutes is greater than a span of 1 hour and 40 minutes.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer



// TimeSpan.java (modified TimeSpan class)
public class TimeSpan implements Comparable
{
	// refer the textbook for the TimeSpan class
	
	/* implementation of the compareTo method of 
		the Comparable interface */
	public int compareTo(TimeSpan other)
	{
		if(totalMinutes < other.totalMinutes)
			return -1;
		else if(totalMinutes > other.totalMinutes)
			return 1;
		else
			return 0;
	}	
}

// TimeSpanDemo.java
import java.util.ArrayList;
import java.util.Collections;
public class TimeSpanDemo
{
	public static void main(String[] args)
	{
		TimeSpan ts1 = new TimeSpan(3, 15);
		TimeSpan ts2 = new TimeSpan(1, 40);
		TimeSpan ts3 = new TimeSpan(4, 10);
		TimeSpan ts4 = new TimeSpan(2, 50);

		ArrayList timeSpans = new ArrayList();
		timeSpans.add(ts1);
		timeSpans.add(ts2);
		timeSpans.add(ts3);
		timeSpans.add(ts4);

		System.out.println("Time spans in the list before soring: "
						+ timeSpans);

		Collections.sort(timeSpans);

		System.out.println("Time spans in the list after soring: "
						+ timeSpans);
	}
}

Output :


Time spans in the list before soring: [3h 15m, 1h 40m, 4h 10m, 2h 50m]
Time spans in the list after soring: [1h 40m, 2h 50m, 3h 15m, 4h 10m]
0 0

Discussions

Post the discussion to improve the above solution.