Is there a library for comparing values ​​of a primitive type?

I implement an interface Comparablein a trivial class that wraps one member int.

I can implement it like this:

    @Override
    public int compareTo ( final MyType o )
    {
        return
            Integer.valueOf( this.intVal ).compareTo(
                Integer.valueOf( o.intVal )
            );
    }

But this (possibly) creates 2 completely unnecessary Integer objects.

Or I can use a proven and truthful approach in the 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));
    }

It is quite efficient, but duplicates the code unnecessary.

Is there a library that implements this missing method Integer(both Double and Float)?

   public static int compare ( int v1, int v2 );
+5
source share
4 answers

In Java 7, static int comparefor primitive types were added to all shell classes of primitive objects, that is now:

java.lang.Integer: static int compare( int x, int y );
java.lang.Byte: static int compare( byte x, byte y );
java.lang.Short: static int compare( short x, short y );
etc...
+6
source

, , . Integer, compare, , , .

+6

, - , .

, Integer ( Double Float)?

public static int compare ( int v1, int v2 );

, , :

public static int compare ( int v1, int v2 )
{
    if (v1 < v2) return -1;
    if (v1 > v2) return  1;
    return 0;
}
+2

, , , :

public static int compare ( int v1, int v2 )
{
    return v1 - v2;
}

Note: @aix is ​​right! This approach will not work for arbitrary integers. It will work for positive integers, although, for example, automatically generated database keys, etc.

-1
source

All Articles