JAVA ArrayList implements sorting

We first generate 20 random numbers and store them in ArrayList

ArrayList<Integer> al=new ArrayList<>();
        Random r=new Random();
        for (int i=0;i<20;i++) {
    
    
            al.add(r.nextInt(100));
        }

The output is as follows
Insert picture description here


There are two implementation forms for the sorting of ArrayList
  1. Sort using Collections
  2. Use the sort() that comes with ArrayList

The two methods are actually similar

Sorting of Collections

Here when using sort() in Collections, we also require a comparator to
be passed in . This is also very understandable. Sometimes the contents of the array we want to pass in may not be real numbers, but also objects. At this time, if you call sort directly, the system There is no way to know what you want to sort by.
Insert picture description here


Here we are sorting the integers, first write a comparator by ourselves

class SortByIndex implements Comparator<Integer> {
    
    

    @Override
    public int compare(Integer o1, Integer o2) {
    
    
        if(o1>o2) {
    
    
            return 1;
        }
        return -1;
    }
}

Then we pass in the sort() just now
Insert picture description here


This can be sorted successfully
Insert picture description here


ArrayList comes with sorting

In fact, it is similar to Collection, so I will put the code directly here.

public class ArrayListTest {
    
    

    public static void main(String[] args) {
    
    

        ArrayList<Integer> al=new ArrayList<>();
        Random r=new Random();
        for (int i=0;i<20;i++) {
    
    
            al.add(r.nextInt(100));
        }
        outputStringArrayList(al);

//        Collections.sort(al,new SortByIndex());
        al.sort(new SortByIndex());

        System.out.println("排序后为:");
        outputStringArrayList(al);
    }

    public static void outputArrayList(ArrayList<Integer> arr) {
    
    
        Iterator<Integer> it=arr.iterator();
        while(it.hasNext()) System.out.print(it.next()+" ");
        System.out.println();
    }

    public static void outputStringArrayList(ArrayList<Integer> arr) {
    
    
        String str=arr.toString();
        System.out.println(str);
    }

    public static void outputStringLinkedList(LinkedList<Integer> ll) {
    
    
        String str=ll.toString();
        System.out.println(str);
    }
}

class SortByIndex implements Comparator<Integer> {
    
    

    @Override
    public int compare(Integer o1, Integer o2) {
    
    
        if(o1>o2) {
    
    
            return 1;
        }
        return -1;
    }
}

Guess you like

Origin blog.csdn.net/weixin_44062380/article/details/107182347