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

Tor*_*ups 17 java sorting comparable

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

当前的obj实现类似于下面的内容.在我正在使用的课程中,我称之为Collections.sort(树);

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

    public int compareTo(Tree o) {
        return this.dist.compareTo(o.dist);
    }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*off 30

如果你有一个想要对long值进行排序的对象,并且它实现了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);
  }
}
Run Code Online (Sandbox Code Playgroud)

调用Collections.sort(my_objects)my_objects之类的地方

  List<MyObject> my_objects = new ArrayList<MyObject>();
  // + some code to populate your list
Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于API级别19 (9认同)

rat*_*eak 17

为什么不在那里存储很长时间:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 更新:从Java 7开始,你可以做`Long.compare(x,y);`而不是自己编写这样的代码(不是革命,而是更简单). (26认同)
  • 在Android中,@ ChristopheRoussy的解决方案仅适用于API 19及更高版本. (7认同)

小智 13

好吧,如果dist变量实际上很长,那么你可能会尝试使用

public int compareTo(Tree o) {
    return Long.valueOf(this.dist).compareTo(Long.valueOf(o.dist));
}
Run Code Online (Sandbox Code Playgroud)

  • S/parseLong /的valueOf / (3认同)

dja*_*fan 5

只是我使用 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;
}
Run Code Online (Sandbox Code Playgroud)