Breaking News
Home / Java / Java FAQ / Comparator for Primitive Types in Java

Comparator for Primitive Types in Java

/**
* Collected methods which allow easy implementation of equals. Example use case in a class called Car:
*

  1. public boolean equals(Object that)
  2.  {
  3.         if (this == that)
  4.                 return true;
  5.         if (!(that instanceof Car))
  6.                 return false;
  7.         Car thatCar = (Car) that;
  8.         return Comparator.areEqual(this.fName, that.fName) && Comparator.areEqual(this.fNumDoors, that.fNumDoors)
  9. && Comparator.areEqual(this.fGasMileage, that.fGasMileage) && Comparator.areEqual(this.fColor, that.fColor)
  10. && Arrays.equals(this.fMaintenanceChecks, that.fMaintenanceChecks); //array!
  11.  }

*
* Arrays are not handled by this class. This is because the Arrays.equals methods should be
* used for array fields.
*/

<!>

  1. package com.livrona.comono.comparator;
  2.  
  3. public final class EqualityComparator
  4. {
  5.         public static boolean areEqual(boolean aThis, boolean aThat)
  6.         {
  7.                 return aThis == aThat;
  8.         }
  9.  
  10.         public static boolean areEqual(char aThis, char aThat)
  11.         {
  12.                 return aThis == aThat;
  13.         }
  14.  
  15.         public static boolean areEqual(double aThis, double aThat)
  16.         {
  17.                 return Double.doubleToLongBits(aThis) ==   Double.doubleToLongBits(aThat);
  18.         }
  19.  
  20.         public static boolean areEqual(float aThis, float aThat)
  21.         {
  22.                 return Float.floatToIntBits(aThis) ==  Float.floatToIntBits(aThat);
  23.         }
  24.  
  25.         public static boolean areEqual(long aThis, long aThat)
  26.         {
  27.                 return aThis == aThat;
  28.         }
  29.  
  30.         public static boolean areEqual(Object aThis, Object aThat)
  31.         {
  32.                 return aThis == null ? aThat == null : aThis.equals(aThat);
  33.         }
  34. }
[pb_builder]

Check Also

When is OCAJP Java certification going live?

After completing the BETA phase of testing last year, the Oracle’s new OCAJP Java certification, …

Advertisment ad adsense adlogger