Tom
Tom

Reputation: 21

Arraylist.sort asking for a comparator

I have the following code, don't know why there's an error at list.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:

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)

Upvotes: 0

Views: 2099

Answers (2)

Michael
Michael

Reputation: 44250

If you look at the documentation, you'll see that this function requires a Comparator. A comparator is effectively just a function which tells the sort function how to sort - sort low-to-high, sort high-to-low, sort all the even numbers first etc.

The Comparator class provides some commonly used comparators for your convenience, but there's no reason you can't write your own if you require some unusual sorting.

Assuming you want "natural ordering" of integers (low-to-high), you can use:

list.sort(Comparator.naturalOrder());

If you want to sort high-to-low, you can use:

list.sort(Comparator.reverseOrder());

Upvotes: 3

Harish Barma
Harish Barma

Reputation: 634

You can use java.util.Collections.sort(list); if you want to sort the list.

For the sort() method of ArrayList (from Java 8) you have to pass the Comparator as an argument. The comparator can also be passed as null only if the the elements of the list follow the natural ordering.In this case Integer follows natural ordering.

Natural Ordering : The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false. (Copied and pasted from oracle docs) so

Using ArrayList.sort(From Java 8):

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

Using Collections.Sort

Collections.Sort(list);

both will sort the list in the ascending order.

Upvotes: 1

Related Questions