Reputation: 121
I have an Array with 100 objects in it, every object has a long value.
I can get the long value by object.getlongValue()
.
How do I use Comparable to compare those two values?
What I did:
public class objects implements Comparable<objects>{
private long longValue;
public object(long longValue){
this.longValue = longValue;
}
public long getLongValue(){
return longValue;
}
@Override
public int compareTo(object obj) {
return this.compareTo(obj.getLongValue); //now he can't find compareTo
}
And later in when I need to sort the Array, I do the following:
Arrays.sort(ListOfObj, new Comparator<objects>() {
@Override
public int compare(objects obj, objects obj1) {
return obj.getLongValue().compareTo(obj1.getLongValue());
// Here he dosen't know "compareTo" either
}
});
Of cause this is NOT the real Object class, this is just for debugging.
Upvotes: 0
Views: 733
Reputation: 3893
long
is primitive in Java and has no compareTo
method. But, you can box it to Long
:
@Override
public int compareTo(object obj)
return new Long(this.getLongValue()).compareTo(new Long(obj.getLongValue()));
}
or just use signum
function:
Long.signum(this.getLongValue() - obj.getLongValue());
Upvotes: 1