Task 9 of 11 · 0 solved · 11 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.3 Lists — sorting a list

Lesson

Не пишите сортировку сами

Java sorts a list for you: Collections.sort(list). It rearranges the list in place — it returns nothing, it changes the list you gave it.


Worked example

import java.util.Collections;

Collections.sort(names);   // names is now sorted
System.out.println(names);

Numbers go in increasing order, strings alphabetically — the same order compareTo gives. Note the import: Collections lives in java.util like ArrayList.

Careful with the common mistake names = Collections.sort(names); — the method returns nothing, so this does not compile.


▶ Try it: run this, then change something and run it again.



Collections.sort(list)...


Strings are sorted...


Type exactly what this program prints.

import java.util.ArrayList;
import java.util.Collections;

public class Main { public static void main(String[] a){
    ArrayList<Integer> n = new ArrayList<Integer>();
    n.add(3); n.add(1); n.add(2);
    Collections.sort(n);
    System.out.println(n);
}}

Why does list = Collections.sort(list); fail?


True or false?