Comparing Long values using Collections.sort(object)
Long.compare( x , y )
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
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);
}
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));
}