使用Collections.sort(object)来比较Long值

| 我正在尝试按一个长对象对一个简单的对象列表进行排序-以下内容不起作用,因为长字符串之一被推到顶部只是因为它以较低的数字开头。所以我正在寻找一种方法,可以根据实际的长值直接对这些值进行排序 当前的obj实现如下所示。在该类中,我将其称为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);
    }
}
    
已邀请:
        为什么不实际在其中存放很长时间:
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;
    }
}
或先比较字符串的长度,然后再比较它们
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);
}
    
        如果您有一个要按长值排序的对象,并且该对象实现了Comparable,则在Java 7+中,可以使用
Long.compare(long x, long y)
(返回一个int) 例如。
public class MyObject implements Comparable<MyObject>
{
  public long id;

  @Override
  public int compareTo(MyObject obj) {
    return Long.compare(this.id, obj.id);
  }
}
调用
Collections.sort(my_objects)
,其中my_objects类似于
  List<MyObject> my_objects = new ArrayList<MyObject>();
  // + some code to populate your list
    
        好吧,如果dist变量实际上很长,那么您可以尝试使用
public int compareTo(Tree o) {
    return Long.valueOf(this.dist).compareTo(Long.valueOf(o.dist));
}
    
        我使用Long比较器按日期对文件进行排序的一个示例:
public File[] getAllFoldersByDescendingDate(File folder) {
    if (!folder.isDirectory()) {
        return null;
    }
    allFiles = folder.listFiles();
    Arrays.sort(allFiles, new Comparator<File>()
    {
        public int compare(final File o1, final File o2)
        {
            return Long.compare(o2.lastModified(), o1.lastModified());
        }
    });
    return allFiles;
}
    
        这取决于您想做什么?您要保持Comparable的当前实现吗?如果是,请使用带比较器的sort方法,并实现一个自定义比较器,该比较器使用字符串的实际“ long”值(
Long.parseLong(dist)
)。如果否,则只需修改当前的
compareTo
并使用\“ dist \”的Long值。 顺便说一句,我会重新思考一下逻辑并问自己为什么\ dist实际上是Long类型时,为什么它是String类型的?     
        为什么不
public class Tree implements Comparable<Tree> {
    public Long dist;

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

要回复问题请先登录注册