我正在尝试通过将 LinkedList myQueue 中的日期集合清空到 ArrayList myArrayList 中,通过比较器对其进行排序,然后遍历链表以将每个日期放回 myQueue 来对 LinkedList myQueue 中的日期集合进行排序。
一切正常,直到我出于某种原因将日期对象发送到我的比较器中将我创建的日期转换为比较器中的日期不起作用。
这是日期的格式:
Thu Jul 30 00:00:00 JST 1908
这是错误:
Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to Date
at DateComparator.compare(DateComparator.java:14)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at QueueTest.main(QueueTest.java:76)
这是我将 myQueue 中的所有对象放入 myArrayList 的位置:
if (!myQueue.isEmpty()) {
//Collections.sort(myQueue, new DateComparator());
Object nextDate;
ArrayList myArrayList = new ArrayList();
while(!myQueue.isEmpty()){
nextDate = myQueue.removeFirst();
myArrayList.add(nextDate);
}
Collections.sort(myArrayList, new DateComparator());
Iterator it=myArrayList.iterator();
while(it.hasNext()){
myQueue.addLast(it.next());
}
这就是我的比较器中的问题所在:
Date d1 = (Date) a;
Date d2 = (Date) b;
我刚开始在冲绳上计算机科学学校,除了我的狗之外,没有人可以真正谈论这个问题,因此感谢您的帮助。
//编辑:
这是我的教授要求我们用来创建日期对象的 Date() 超类:
public class Date {
private static int numberDates=0;
public static final int VALID_START_YEAR=1584;
private int year;
private int month;
private int day;
public Date() {
month = 1;
day = 1;
year = 1970;
numberDates++;
}
public Date(int newMonth, int newDay, int newYear) {
month = newMonth;
day = newDay;
year = newYear;
numberDates++;
}
public Date( Date other) {
month = other.month;
day = other.day;
year = other.year;
numberDates++;
}
public Date( String date) {
java.util.StringTokenizer st = new java.util.StringTokenizer(date,"/");
month = Integer.parseInt(st.nextToken()); //extract next token
day = Integer.parseInt(st.nextToken());
year = Integer.parseInt(st.nextToken());
numberDates++;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public String toString() {
return(month + "/" + day + "/" + year);
}
public static int getNumberDates() {
return numberDates;
}
public void increment() {
day++; //stub for the actual method to be written later...
}
public static void clearNumberDates() {
numberDates = 0;
}
public static boolean isValidDay(int month, int day, int year) {
return true;
}
public boolean equals( Object other ) {
if ((other instanceof Date) &&
((((Date)other).year==year) &&
(((Date)other).month==month) &&
(((Date)other).day==day)))
return true;
else
return false;
}
public int hashCode() {
return (year + month + day) % 101;
}
public int compareTo( Date other ) {
if (equals(other))
return 0;
else if (year < other.year)
return -1;
else if (year > other.year)
return 1;
else if (month < other.month)
return -1;
else if (month > other.month)
return 1;
else if (day < other.day)
return -1;
else if (day > other.day)
return 1;
else
return 0;
}