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

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

问题描述

对包含数字的ArrayList<String>(以降序/升序方式)进行排序的最快方法是什么?例如:{ "12", "3.5", "188", "33.03" }? Collections是否为此具有内置方法?当前,我将ArrayList的内容复制到ArrayList<Double>,然后使用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天全站免登陆