JAVA中List的sort方法参数到底填什么

论JAVA中List的sort方法参数到底填什么

这是代码

import java.util.*;
public class Main {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> list = new ArrayList<>();
        Random r = new Random();
        for (int i = 0; i < 10; i++)
            list.add(r.nextInt(100));
        list.sort((a, b) -> {
    
    
            if (a > b)
                return 1;//返回值大于0,a应该排在b后面
            else if (a < b)
                return -1;//返回值小于0,a应该排在b前面
            else
                return 0;//返回值为0,不动
        });
        for (int i : list) {
    
    
            System.out.print(i);
            System.out.print(' ');
        }
        System.out.print('\n');
    }
}

这是输出:4 11 12 15 20 24 61 62 74 86

所以说

  • 圆括号里参数a在左b在右,返回正数a就会靠近List末尾
  • 也就是说小排前大排后

清楚了没

猜你喜欢

转载自blog.csdn.net/dscn15848078969/article/details/108561506