使用Collections.sort(object)比较Long值 [英] Comparing Long values using Collections.sort(object)

查看:375
本文介绍了使用Collections.sort(object)比较Long值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按顺序对一个简单的对象列表进行排序 - 以下内容不起作用,因为其中一个长字符串被推到顶部只是因为它以较低的数字开头。所以我正在寻找一种直接按实际长值排序的方法

I'm trying to sort a simple list of objects by a long - the below isn't working because one of the long strings is pushed to the top simply because it starts with a lower number. So I'm looking for a way to sort these by the actual long values directly

当前的obj实现如下所示。在我正在使用它的类中,我调用Collections.sort(trees);

The current obj implementation looks something like the below. In the class I'm using this I call Collections.sort(trees);

public class Tree implements Comparable<Tree> {
    public String dist; //value is actually Long

    public int compareTo(Tree o) {
        return this.dist.compareTo(o.dist);
    }
}


推荐答案

为什么实际上并没有在那里存储长:

why not actually store a long in there:

public class Tree implements Comparable<Tree> {
    public long dist; //value is actually Long

    public int compareTo(Tree o) {
        return this.dist<o.dist?-1:
               this.dist>o.dist?1:0;
    }
}

那个或首先比较字符串的长度然后比较它们

that or first compare the length of the strings and then compare them

public String dist; //value is actually Long
public int compareTo(Tree o) {
    if(this.dist.length()!=o.dist.length())
          return this.dist.length()<o.dist.length()?-1:1;//assume the shorter string is a smaller value
    else return this.dist.compareTo(o.dist);
}

这篇关于使用Collections.sort(object)比较Long值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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