簡體   English   中英

如何在Java中對泛型類型列表進行排序

[英]How to sort a list of generic types in Java

我有一組所有共享一些共同屬性的類,所以我讓它們都擴展了一個共同的基類BaseEntity 所以我有,例如Foo extends BaseEntityBar extends BaseEntity

我還希望這些FooBar對象的列表是可排序的,所以我已經實現了Comparable 我將類定義為Foo extends BaseEntity implements Comparable<Foo>Bar extends BaseEntity implements Comparable<Bar> ,並且FooBar的列表的排序按預期工作 - 當然,排序的細節是不同的在不同的子類中。 但是,當我事先不知道我是否會有FooBar時,我無法弄清楚如何進行分類工作。 例如,此代碼無法編譯:

public class UtilityClass<T extends BaseEntity> {

  ...bunch of stuff...

  List<T> values;

  public List<T> sort() {
    Collections.sort(values);
    return values;
  }

  ...more methods...
}

錯誤消息Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<T>). The inferred type T is not a valid substitute for the bounded parameter <T extends Comparable<? super T>> Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<T>). The inferred type T is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

我認為問題是我試圖對BaseEntity對象列表進行排序,而BaseEntity本身並沒有實現Comparable 但現在我面臨一個問題:唯一明智的事情,使BaseEntity對象堪比是其他BaseEntity對象,但是當我添加implements Comparable<BaseEntity>BaseEntity ,編譯器告訴我,我有問題,因為現在我Foo類試圖同時實現Comparable<BaseEntity>Comparable<Foo> ,這顯然是不允許的。

我知道我可以通過刪除implements Comparable<Foo>並實現Comparable<BaseEntity>來回避這個問題,但是然后我的compareTo方法將不得不做丑陋的轉換,我認為這正是使用泛型的那種問題應該是避免。

我真正想要做的是在BaseEntity的簽名中指定它的所有子類都是Comparable ,但僅限於同一子類的實例。

感激地收到任何幫助。 謝謝!

使用交集類型,如下所示:

public class MyList<T extends BaseEntity & Comparable<T>> {...}

這指定T必須既是BaseEntity 是自身Comparable

不要使用Collections.sort(List<T>) ,而是使用Collections.sort(Lst<T>, Comparator<? extends T>) 在比較器中寫下比較代碼。

嘗試這個:

static <T extends Comparable<? super T>> sort(T[] array);

這是完成任務的最通用規范。 基本上,它斷言,T是一種可以與自身進行比較的類型。

您可以創建一個超級簡單的排序方法,可以處理幾乎任何List類型

public class Tools {

    public static <E> void sortList(List<E> list, Comparator<E> comparator) {
        Collections.sort(list, comparator); 
    }

    // Any other utility methods/resources you want in here

}

這意味着只要給定的List和Comparator具有彼此相同的Type,就可以調用此方法對任何List進行排序。 即使沒有你擁有的基類,它也能工作(BaseEntity)

暫無
暫無

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

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