簡體   English   中英

與arrayList的Sorting元素有關的問題

[英]Trouble with Sorting element of arrayList

我在這方面遇到了麻煩,無法克服。 我有一個存儲的arrayList。

public class Application {

Time startTime = new Time(hour,minute);
Time endTime = new Time((startTime.getHour()), (startTime.getMinute() + duration));
Event e1 = new Event("Lecture", title, startTime, endTime);

我想根據我的endTime對事件進行排序,我遇到的問題是endTime基於startTime,它使用了Time類中的小時和分鍾。 當我嘗試使用compareTo我感到困惑。 我將其放在Time類中,但隨后意識到它必須在Event類中才能比較實例。 我將如何使用compareTo比較結束時間,以及如何輸出排序。 當我在事件中添加compareTo時,我得到了

The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Event>)

            Collections.sort(events);

public Event(String type, String title, Time startTime, Time endTime) {
    this.type = type;
    this.title = title;
    this.startTime = startTime;
    this.endTime = endTime;
}

private int minute;

public Time(int hour, int minute) {
    this.minute = hour * 60 + minute;
}

我也可以extend一個類,還是必須實現它以使用compareTo

我將如何使用compareTo比較結束時間,

compareTo為你的方法Event類將調用compareTo上你的方法Time類,並使用結果作為確定事件順序的一部分。

以及如何輸出排序。

一種方法是使用循環並進行printprintln調用。

當我在事件中放入compareTo時,我得到: "The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Event>)"

events的類型聲明為List<Event>

順便說一句,將compareTo放在事件中並不會導致這種情況。 那是由另一個變化/另一個錯誤引起的。

我也可以擴展一個類,還是必須實現它以使用compareTo

任何需要比較的類都需要使用自己的類型作為類型參數來“實現” Comparable接口。 例如

public class Event implements Comparable<Event> {

然后,它需要提供compareTo方法的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM