簡體   English   中英

Collections.sort(emptyList()):無法推斷類型變量

[英]Collections.sort(emptyList()): cannot infer type-variable

什么? 使用javac (1.8.0_121)會發生此編譯錯誤,但在Eclipse(4.6.2)中構建並運行良好。

一個極小的代碼如下:

import java.util.Collections;

public static void main(String[] args) {
    Collections.sort(Collections.emptyList());
}

(我不關心語義。原始代碼不是Collections.sort()而是具有類似簽名的東西。)

為此, javac打印:

error: no suitable method found for sort(List<Object>)
                Collections.sort(Collections.emptyList());
                           ^
    method Collections.<T#1>sort(List<T#1>) is not applicable
      (inferred type does not conform to upper bound(s)
        inferred: Object
        upper bound(s): Comparable<? super Object>,Object)
    method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))
  where T#1,T#2 are type-variables:
    T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
    T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
1 error

有什么我可以做javac來進行編譯嗎? 我是否應該將此視為Java 8中的限制並編寫解決方法?

更改為Collections.<Comparable<Object>>sort(Collections.emptyList()); 讓它編譯。

有點老問題,但仍然沒有接受的答案。

假設對象是可比較的,比如String類,我只需更改如下:

Collections.sort(Collections.<String>emptyList());

或者將其分為兩步:

List<String> s = Collections.emptyList();
Collections.sort(s);

如原始問題中更新的那樣,如果您不想對Collections.emptyList()進行任何更改,則以下內容也適用:

Collections.<Comparable<Object>>sort(Collections.emptyList());

暫無
暫無

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

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