2017-08-03 23 views
0

我有下面的代碼,不知道爲什麼有一個在list.sort錯誤Arraylist.sort要求比較

public class Ccc{ 

    public static void main(String[] args)throws IOException,ParseException{ 
     File inFile = new File("C:\\Users\\shyic\\Desktop\\senior_data\\s3\\s3.27.in"); 
     Scanner in = new Scanner (inFile); 
     int length = Integer.parseInt(in.nextLine()); 
     ArrayList<Integer> list = new ArrayList<>(); 
     while(in.hasNext()){ 
      list.add (in.nextInt()); 
     } 
     list.sort(); 
     for (int i =0;i<10000;i+=1000){ 
      System.out.println(list.get(i)); 
     } 
    } 
} 

錯誤:

Error:(21, 13) java: no suitable method found for sort(no arguments) 
    method java.util.List.sort(java.util.Comparator<? super java.lang.Integer>) is not applicable 
     (actual and formal argument lists differ in length) 
    method java.util.ArrayList.sort(java.util.Comparator<? super java.lang.Integer>) is not applicable 
     (actual and formal argument lists differ in length) 
+2

錯誤消息是不言自明的 - ''ArrayList'沒有'sort()'方法,但它有一個'sort(Comparator)'方法。 – assylias

+1

使用'Collections.sort(list);' – Eran

+0

您應該閱讀[List#sort'的文檔](https://docs.oracle.com/javase/8/docs/api/java/util/List。 html#sort-java.util.Comparator-) –

回答

2

如果你看看the documentation,你會發現這個功能需要Comparator。一個比較有效的就是它告訴排序功能如何排序功能 - 排序從低到高,排序高到低,排序所有的偶數第一等

Comparator類提供了一些常用爲了您的方便使用了比較器,但如果您需要一些不尋常的排序,則沒有理由不能編寫自己的代碼。

假設你想整數(從低到高)的「自然順序」,您可以使用:

list.sort(Comparator.naturalOrder()); 

如果要排序從高至低,你可以使用:

list.sort(Comparator.reverseOrder()); 
+0

非常感謝!解決問題 – Tom

+0

@Tom接受它 –

1

你可以,如果你使用java.util.Collections.sort(list);想要對列表進行排序。

對於ArrayList(來自Java 8)的sort()方法,您必須將比較器作爲參數傳遞。只有當列表中的元素遵循自然順序時,比較器纔可以作爲null傳遞。在這種情況下,整數遵循自然順序。

自然排序:當且僅當e1.compareTo(e2)== 0與每個e1.equals(e2)具有相同的布爾值時,C類的自然順序被認爲與equals相一致請注意,null不是任何類的實例,即使e.equals(null)返回false,e.compareTo(null)也應拋出NullPointerException。 (複製和粘貼oracle docs)使用ArrayList.sort 所以

(從Java 8):使用

list.sort(null); // Integer follows natural ordering 

Collections.Sort

Collections.Sort(list); 

都將排序列表按升序排列。

+0

我非常不喜歡傳遞一個null參數給'list.sort'。我認爲這是一個設計監督。最好是具體說明Comparator.naturalOrder()的意圖,因爲這意味着未來的代碼維護者不必知道那些愚蠢的實現細節。 – Michael

+1

謝謝你的啓發。我不知道。和upvote –