Java byte array compare for differences

Description

Java byte array compare for differences

public class Main {

   public static void main(String[] argv){
      byte[] b = "demo2s.com".getBytes();
      byte[] a = "Demo2s.com".getBytes();
      System.out.println(notEquals(a,b));
   }// w  w w .  j  av a2s. c  o m
   /**
    * Compare two byte[] for differences, either may be null
    *
    * @param a One byte[].
    * @param b The other byte[].
    * @return true if the byte[]s are different, false if they are the same.
    */
   public static boolean notEquals(byte[] a, byte[] b) {
      // if both null, they are the same
      if ((a == null) && (b == null))
         return false;

      // if either are null (they both are not), they are different
      if ((a == null) || (b == null))
         return true;

      // if the lengths are different, they are different
      if (a.length != b.length)
         return true;

      // now we know neither are null, so compare, item for item (order counts)
      for (int i = 0; i < a.length; i++) {
         if (a[i] != b[i])
            return true;
      }

      // they are NOT different!
      return false;
   }

}



PreviousNext

Related