I am implementing Comparable
interface on a trivial class that wraps a single int
member.
I can implement it this way:
@Override
public int compareTo ( final MyType o )
{
return
Integer.valueOf( this.intVal ).compareTo(
Integer.valueOf( o.intVal )
);
}
But this (maybe) creates 2 totally unnecessary Integer objects.
Or I can go tried and true cut-and-paste approach from Integer class:
@Override
public int compareTo ( final MyType o )
{
int thisVal = this.intValue;
int anotherVal = o.intValue;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
This is pretty efficient, but duplicates code unnecessary.
Is there a library that would implement this missing Integer
( and Double and Float ) method?
public static int compare ( int v1, int v2 );
compareTo()
to a new method that takes two arguments instead of usingthis
? – Studley