【问题标题】:How to sort arrayList according to Integer size in android?如何根据android中的整数大小对arrayList进行排序?
【发布时间】:2014-06-19 01:39:25
【问题描述】:

我正在使用“compareTo(String string);”对数组列表 int 项进行排序这种方法只比较字符串而不比较整数值。如何根据整数值对数组列表进行排序。

这是我的代码:

 Collections.sort(mAllSpeedsArray, new AllSpeedsComparator());

public class AllSpeedsComparator implements Comparator<AllSpeeds> {

@Override
public int compare(AllSpeeds lhs, AllSpeeds rhs) {
    // TODO Auto-generated method stub      
        return lhs.getSpeed().compareTo(rhs.getSpeed());        
    }
}

【问题讨论】:

  • 抱歉,时间还早。不是 Collections.swap(),Collections.sort(allSpeedsArray);
  • 也许另一种可能性是将字符串转换为整数,然后比较它们(>等...)。转换:int stringVal = Integer.parseInt("myString");
  • 将我的评论与@smagnan 混合起来,对我来说看起来既快捷又简单:P
  • 是的@smagnam 我试过这个,但我没有得到准确的排序。

标签: java android sorting arraylist comparator


【解决方案1】:

要么让您的 AllSpeeds 数据结构从 getSpeed() 返回 int(或 double,或其他数字),要么在两个字符串上使用 Integer.parse(string),然后比较整数。

【讨论】:

  • 像这样 int firstSpeed = Integer.parseInt(lhs.getSpeed()); int secondSpeed = Integer.parseInt(rhs.getSpeed());
  • 我正在像这样比较这两个 Inegers if (firstSpeed
  • 但它总是只执行 else 块。
  • 您可以返回firstSpeed - secondSpeed
【解决方案2】:

这个怎么样

@Override
public int compare(AllSpeeds lhs, AllSpeeds rhs) {
    // TODO Auto-generated method stub      
    int a = Integer.parseInt(lhs.getSpeed());
    int b = Integer.parseInt(rhs.getSpeed());
    return a < b ? 1 : (a == b ? 0 : -1);
}

【讨论】:

  • 返回方法给出“不能从字符串转换为整数”错误。因为我的 getSpeed() 是字符串类型。
  • 更新一个给出“不能在原始类型 int 上调用 compareTo(int)”
猜你喜欢
  • 1970-01-01
  • 2017-07-06
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
相关资源
最近更新 更多