You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by Steve Downey <st...@netfolio.com> on 2002/09/13 05:40:56 UTC

[lang]CompareTo method for Doubles

In JDK 1.4, there's a method that has exactly the right contract for doing 
Compare that matches up with EqualsBuilder and HashCodeBuilder. 

static int Double.compare(double, double)

It does the same comparison as Double.compareTo(Double), only on primitive 
values.

For CompareToBuilder, I don't like the idea of creating Doubles just to do the 
comparisons, it's a lot of overhead. So this is what I've got for reverse 
engineering the new static method in JDK 1.4

  
  int compare(double lhs, double rhs) {
  	if (lhs < rhs) {
  		return -1;
  	}
  	if (lhs > rhs) {
  		return +1;
  	}
  	//Need to compare bits to handle 0.0 == -0.0 being true
  	// compare should put -0.0 < +0.0
  	// Two NaNs are also == for compare purposes
  	// where NaN == NaN is false
  	long lhsBits = Double.doubleToLongBits(lhs);
  	long rhsBits = Double.doubleToLongBits(rhs);
  	if (lhsBits == rhsBits) {
  		return 0;
  	}
  	//Something exotic! A comparison to NaN
  	//Fortunately NaN's long is > than everything else
        //Also negzeros bits < poszero
  	//NAN: 9221120237041090560
  	//MAX: 9218868437227405311
        //NEGZERO: -9223372036854775808
        //ZERO: 0
  	if (lhsBits < rhsBits) {
  		return -1;
  	} else {
  		return +1;
  	}
  }



--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>