Java重写compare方法实现数组降序排列

2020-07-16 15:31:53 浏览数 (1)

代码语言:javascript复制
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        int index = scanner.nextInt();
        String[] s = str.split(" ");
        List<String> strings = Arrays.asList(s);
        Collections.sort(strings, new Comparator<String>() {
            //重写排序方法
            @Override
            public int compare(String o1, String o2) {
                int one = Integer.parseInt(o1);
                int two = Integer.parseInt(o2);
                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println(strings.get(index - 1));
    }
}

0 人点赞