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:
Inheritance And Interfaces
Exercise:
Exercises
Question:11 | ISBN:9780136091813 | Edition: 2

Question

Add an equals method to the TimeSpan class introduced in Chapter 8. Two time spans are considered equal if they represent the same number of hours and minutes.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package inheritance;

public class TimeSpan {

	private int hours;
	private int minutes;

	// Construtor to pass hours and minutes
	public TimeSpan(int hours, int minutes) {
		this.hours = 0;
		this.minutes = 0;
		add(hours, minutes);
	}

	// this methods thorws an error if invalid hours and miutes passes into the
	// argument
	public void add(int hours, int minutes) {
		if (hours < 0 || minutes < 0) {
			throw new IllegalArgumentException();
		}

		this.hours += hours;
		this.minutes += minutes;

		// converts each 60 minutes into one hour
		this.hours += this.minutes / 60;
		this.minutes = this.minutes % 60;
	}

	// returns a String for this time span, such as "6h 15m"
	public String toString() {
		return hours + "h " + minutes + "m";
	}

	// this method overrides the equals method in the Object class
	@Override
	public boolean equals(Object obj) {

		if (obj == null) {
			return false;
		}

		if (obj.getClass() != this.getClass()) {
			return false;
		}

		final TimeSpan ts = (TimeSpan) obj;
		if ((Integer.valueOf(this.hours) == null) ? (Integer.valueOf(ts.minutes) != null)
				: !((Integer.valueOf(this.hours)).equals(Integer.valueOf(ts.hours)))) {
			return false;
		}

		if (this.minutes != ts.minutes) {
			return false;
		}

		return true;
	}

    // if we override equals we should override hashcode() method too
	@Override
	public int hashCode() {

      // chose a random prime number for better hash functionality		
		int hash = 31;
		hash = 17 * hash + (Integer.valueOf(this.hours) != null ? Integer.valueOf(this.hours).hashCode() : 0);
		hash = 17 * hash + this.minutes;
		return hash;
	}

	public static void main(String[] args) {

		TimeSpan elapsed = new TimeSpan(3, 56);
		TimeSpan elapsed1 = new TimeSpan(4, 124);
		TimeSpan elapsed2 = new TimeSpan(3, 56);

		System.out.println(elapsed.equals(elapsed2));
		System.out.println(elapsed1.equals(elapsed2));

	}

}
Output:

true
false

 

0 0

Discussions

Post the discussion to improve the above solution.