Write a class called Time that includes five fields: year, month, day, minutes a
ID: 3733912 • Letter: W
Question
Write a class called Time that includes five fields: year, month, day, minutes and seconds. This class stores information about a single point in time. Your class should have constructor(s), accessors and mutators, and it should implement the Comparable interface. Years take precedence over months, which take precedence over days etc. For example, Feb 19, 2016 comes after Nov 20, 2015. Write a client class TimeTest that creates 3 instances of class Time, initializes them with random values (you can specify the values yourself or use Math.random() function), adds them to ArrayList and sorts the list (you can use Collections.sort()).
Explanation / Answer
Code:
public class Time implements Comparable<Time>{
private int year, month, day, minutes, seconds;
public Time() {
}
public Time(int year, int month, int day, int minutes, int seconds) {
this.year = year;
this.month = month;
this.day = day;
this.minutes = minutes;
this.seconds = seconds;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
@Override
public int compareTo(Time time) {
int cmp = Integer.compare(year, time.year);
if(cmp == 0) {
cmp = Integer.compare(month, time.month);
if(cmp == 0) {
cmp = Integer.compare(day, time.day);
if(cmp == 0) {
cmp = Integer.compare(minutes, time.minutes);
if(cmp == 0) {
return Integer.compare(seconds, time.seconds);
} else {
return cmp;
}
} else {
return cmp;
}
} else {
return cmp;
}
} else {
return cmp;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.