对数字字符串的 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());