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