我有一个Event类,它使用PriorityQueue和我自己定义的Time类用于Event类。
static class Event implements Comparable<Event>{
Customer customer;
Time eventTime;
char eventType;
public int compareTo(Event e){
int n = e.eventTime.compareTo(eventTime);
int compare = 0;
if(n < 0){
compare = -1;
}
else if(n == 0){
compare = 0;
}
else if(n > 0){
compare = 1;
}
return compare;
}
}
class Time{
private int hour;
private int minute;
private boolean isMorning;
public Time(){
hour = 0;
minute = 0;
isMorning = true;
}
public Time(int h, int m, boolean morning){
hour = h;
minute = m;
isMorning = morning;
}
public void setTime(int h, int m, boolean morning){
hour = h;
minute = m;
isMorning = morning;
}
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public boolean isAM(){
return isMorning;
}
public String toString(){
String AM = "";
String min = "";
if(minute < 10){
min = ("0" + minute);
}
else{
min = ("" + minute);
}
if(isMorning){
AM = "AM";
}
else{
AM = "PM";
}
return ("" + hour + ":" + min + " " + AM);
}
public Time plus(int n){
Time newTime = new Time();
boolean newMorning = false;
int minutes = minute + n;
int newHour = minutes/60;
int newMinutes = minutes%60;
hour = hour + newHour;
if(hour > 12){
hour = hour - 12;
if(isMorning){
newMorning = false;
}
else{
newMorning = true;
}
}
newTime.setTime(hour, newMinutes, newMorning);
return newTime;
}
public int timeDifference(Time t){
int n = totalMinutes();
int m = t.totalMinutes();
return m - n;
}
public int compareTo(Time t){
int n = totalMinutes();
int m = t.totalMinutes();
int compare = 0;
if(n < m){
compare = -1;
}
else if(n == m){
compare = 0;
}
else if(n > m){
compare = 1;
}
return compare;
}
private int totalMinutes(){
int tempMinute = 0;
if(!isMorning){
if(hour == 12){
}
else{
hour = hour + 12;
tempMinute = (hour*60) + minute;
}
}
else{
if(hour == 12){
tempMinute = minute;
}
else{
tempMinute = (hour*60) + minute;
}
}
return tempMinute;
}
}
这不是我的所有代码,因为我有其他人只是持有稍后将插入到事件队列中的值。当我检查事件队列之外的时间时它与它应该的时间相匹配,比如我有一个Time对象为11:22 AM,但当我将它插入事件队列时,我的时间变为23:22 AM。由于某种原因,它在事件队列中增加了12个小时,我不明白为什么。
计算出totalMinutes()方法正在弄乱小时,因为在隐式使用compareTo()或timeDifference()时会调用它。谢谢你的帮助!
答案 0 :(得分:0)
首先,totalMinutes()
与hour
字段混淆时不应该。它应该使用局部变量。
其次,您的整个Event.compareTo(Event e)
方法可以简化为
return e.eventTime.compareTo(eventTime);
这是回到前面,除非你想要最近的时间。尝试
return eventTime.compareTo(e.eventTime);