Java sorts the elements (custom class) in the ArrayList collection

Preface

If what is stored in ArraylIst is not a basic type such as an integer, but a reference type such as a custom class, how should we sort it? (The emmm thing edge_lst = sorted(edge_lst, key=lambda x: x.weight)is solved in one sentence in python ... Hematemesis 1 Talk to the young lady today, but I didn’t play well, hematemesis 2)

The sorting here uses the sort static method of the Collections tool class, which means that it can be used without instantiating Collections.

Method 1: The custom class implements the Comparable interface and overrides the compareTo method

What is used here is: public static <T> void sort(List<T> list)
for example:

class Edge implements Comparable<Edge>{
    
    
    public int start;
    public int end;
    public double weight;

    public Edge(int start, int end, double weight) {
    
    
        this.start = start;
        this.end = end;
        this.weight = weight;
    }
    @Override
    public int compareTo(Edge o) {
    
    
        return (int)(this.weight - o.weight);
    }
}
Collections.sort(arr_lst); // 这里的arr_lst是ArrayList<Edge>对象

Method 2: Implement the Comparator interface, which is used as the second parameter of Collections.sort

Here is public static <T> void sort(List<T> list,Comparator<? super T>
an example

Collections.sort(arr_lst, new Comparator<Edge>() {
    
    
            @Override
            public int compare(Edge o1, Edge o2) {
    
    
                return (int)(o1.weight-o2.weight);
            }
        });

Ah, there is this method, but I don't know its principle for the time being. .

arr_lst.sort((Edge o1, Edge o2) -> (int) (o1.weight - o2.weight));

reference

How to sort the elements in the ArrayList collection in Java

Guess you like

Origin blog.csdn.net/jokerxsy/article/details/113840466