Comparing Long values using Collections.sort(object)

放肆的年华 提交于 2019-12-01 02:28:18

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);
}

If you have an object that you want to sort on a long value, and it implements Comparable, in Java 7+ you can use Long.compare(long x, long y) (which returns an int)

E.g.

public class MyObject implements Comparable<MyObject>
{
  public long id;

  @Override
  public int compareTo(MyObject obj) {
    return Long.compare(this.id, obj.id);
  }
}

Call Collections.sort(my_objects) where my_objects is something like

  List<MyObject> my_objects = new ArrayList<MyObject>();
  // + some code to populate your list
cipher

well if the dist variable is actually long then you might try using

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

It depends on how you want to do things? Do you want to keep the current implementation of Comparable? If yes, use the sort method which takes a Comparator and implement a custom comparator which uses the actual "long" values of the string (Long.parseLong(dist)). If no, then just modify the current compareTo and use the Long values of the "dist".

BTW, I'd revisit the logic and ask myself why "dist" is of type String when it is actually a Long?

Just an example I made for sorting Files by date using a Long comparator:

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;
}

Why not

public class Tree implements Comparable<Tree> {
    public Long dist;

    public int compareTo(Tree o) {
        return this.dist.compareTo(o.dist);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!