Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a library to compare primitive type values?

Tags:

java

compareto

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 );
like image 422
Alexander Pogrebnyak Avatar asked Sep 01 '11 16:09

Alexander Pogrebnyak


3 Answers

  • For int, write your own compare method (it requires at most three lines of code).
  • For double, use Double.compare (not to be confused with compareTo).
  • For float, use Float.compare.

The last two take primitive types and thus avoid boxing and unboxing. I can see an argument for Integer providing a similar compare method, but as things stand it doesn't.

like image 135
NPE Avatar answered Oct 10 '22 17:10

NPE


In Java 7, static int compare for primitive types have been added to all primitive object wrapper classes, i.e there 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...
like image 33
Alexander Pogrebnyak Avatar answered Oct 10 '22 19:10

Alexander Pogrebnyak


Maybe, I'm missing something, but IMHO this is a weird question.

Is there a library that would implement this missing Integer ( and Double and Float ) method?

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

Well, I think this does the job:

public static int compare ( int v1, int v2 )
{
    if (v1 < v2) return -1;
    if (v1 > v2) return  1;
    return 0;
}
like image 33
Martijn Courteaux Avatar answered Oct 10 '22 17:10

Martijn Courteaux