且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对数字的字符串的ArrayList进行排序

更新时间:2023-02-21 14:19:51

您需要实现自己的比较器,并在列表中使用它. 您必须使用BigDecimal,因为您可能会遇到精度损失的问题.如果您的数字要求较小的精度,则可以使用double.

You need to implement your own comparator, and use it on your list. You have to use BigDecimal, because you can have problems with loss of precision. You can use double, if your numbers are quire small precision.

class MyComparator implements Comparator<String, String> {

    public int compare(String o1, String o2){
        return new BigDecimal(o1).compareTo(new BigDecimal(o2));
    }

}
...
Collections.sort(list, new MyComparator());