对数字字符串的 ArrayList 进行排序 [英] Sort an ArrayList of Strings that are numbers

查看:63
本文介绍了对数字字符串的 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对包含数字的 ArrayList(以降序/升序方式)进行排序的最快方法是什么,例如:{ "12", "3.5", "188", "33.03" } ?Collections 有内置的方法吗?目前我正在将 ArrayList 的内容复制到 ArrayList,然后使用 Collections.Sort() 方法,然后将其放回初始数组.有没有更快的方法?

What is the fastest way to sort an ArrayList<String> (in descending/ascending manner) that contains numbers, eg: { "12", "3.5", "188", "33.03" } ? Does Collections have a built-in method for this? Currently I am copying the ArrayList's contents to ArrayList<Double> and then using Collections.Sort() method and then putting it back to the initial array. Is there a faster way?

推荐答案

您需要实现自己的比较器,并在您的列表中使用它.您必须使用 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());

这篇关于对数字字符串的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆