javasortingcomparable

Comparing Long values using Collections.sort(object)


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

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

Solution

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