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