踩坑系列之List倒序排序问题

问题描述

项目中利用为数字的字符串转为Integer进行逆序排序,使用Collections.reverse(list);意外失败;不知道为什么总是不能倒序排列。无奈改成Collections.sort(list,Collections.reverseOrder());后成功。

写了个demo测试

package com.jarWorker.demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;

public class TestListSort {
    @Test
    public void testSort() throws Exception {
        List<Integer> intList = new ArrayList<>();
        String str0 = "10";
        String str1 = "90";
        String str2 = "76";
        String str3 = "11";
        String str4 = "5";
        String str5 = "7";
        String str6 = "8";
        Integer number0 = Integer.parseInt(str0);
        Integer number1 = Integer.parseInt(str1);
        Integer number2 = Integer.parseInt(str2);
        Integer number3 = Integer.parseInt(str3);
        Integer number4 = Integer.parseInt(str4);
        Integer number5 = Integer.parseInt(str5);
        Integer number6 = Integer.parseInt(str6);
        intList.add(number0);
        intList.add(number1);
        intList.add(number2);
        intList.add(number3);
        intList.add(number4);
        intList.add(number5);
        intList.add(number6);
        System.out.println("原始排序:" + intList);
        Collections.sort(intList);
        System.out.println("正序排列:" + intList);
        Collections.reverse(intList);
        System.out.println("网上所谓的逆序排列:" + intList);
        Collections.sort(intList, Collections.reverseOrder());
        System.out.println("正确姿势的逆序排列:" + intList);
        System.out.println("这结果还是很意外的哈!!!");
    }
}

 结果

原始排序:[10, 90, 76, 11, 5, 7, 8]
正序排列:[5, 7, 8, 10, 11, 76, 90]
网上所谓的逆序排列:[90, 76, 11, 10, 8, 7, 5]
正确姿势的逆序排列:[90, 76, 11, 10, 8, 7, 5]
这结果还是很意外的哈!!!

结论

还是使用Collections.sort(list, Collections.reverseOrder());稳妥些,毕竟Collections.reverse(list);出现了没有想到的结果bug,特此记录

----------------------------------------------------------------

链接:https://www.jianshu.com/p/e37783154956
来源:简书

猜你喜欢

转载自blog.csdn.net/baidu_25310663/article/details/88388890