In: Computer Science
Java basic sorting problem
Supposed I have a simple array list storing the telephone numbers. How can I sort the numbers in descending order with different ways?
Give ArrayList<String> tel = ["11223344", "55442211", "99881122", "99002211", "34446666", "12342353"]
I come up a solution using Collections.sort(tel), but it requires a compare method and I have no idea its contents and also the position of the method.
Would you suggest 2 or 3 ways and write the code to achieve my purpose?
You can use Collections.sort(tel,Collections.reverseOrder()); to sort the list in descending order.
Or you can first sort the list and then reverse.
Collections.sort(tel);
Collections.reverse(tel);
This will sort the list in descending order.
Sample program and output
import java.util.ArrayList;
import java.util.Collections;
public class Test {
    public static void main(String[] args) {
        ArrayList<String>
tel = new ArrayList();
       
tel.add("11223344");
       
tel.add("55442211");
       
tel.add("99881122");
       
tel.add("99002211");
       
tel.add("34446666");
       
tel.add("12342353");
        ArrayList<String>
copy = (ArrayList<String>) tel.clone();
       
System.out.println("List: "+copy);
       
Collections.sort(tel,Collections.reverseOrder());
        System.out.println("List
after sort in 1st way: "+tel);
      
       
System.out.println("\nList: "+copy);
       
Collections.sort(copy);
        System.out.println("List
after sort: "+copy);
       
Collections.reverse(copy);
        System.out.println("List
after sort and reverse: "+copy);
      
    }
}
