Java Byte Array Equal byteArrayEquals(byte[] a1, byte[] a2)

Here you can find the source of byteArrayEquals(byte[] a1, byte[] a2)

Description

Compare two byte arrays for equality

License

Open Source License

Parameter

Parameter Description
a1 the a1
a2 the a2

Return

true, if they are equal (both null is considered equal)

Declaration

public static boolean byteArrayEquals(byte[] a1, byte[] a2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**// ww w .j  a  v a2  s. c  om
     * Compare two byte arrays for equality
     *
     * @param a1 the a1
     * @param a2 the a2
     * @return true, if they are equal (both null is considered equal)
     */
    public static boolean byteArrayEquals(byte[] a1, byte[] a2) {
        return byteArrayEquals(a1, 0, a2, 0, a1 == null ? 0 : a1.length);
    }

    /**
     * Compare two byte arrays for equality
     *
     * @param a1 the a1
     * @param a1Pos starting compare source index
     * @param a2 the a2
     * @param a2Pos starting compare dest index
     * @param length the length
     * @return true, if successful
     */
    @SuppressWarnings("null")
    public static boolean byteArrayEquals(byte[] a1, int a1Pos, byte[] a2,
            int a2Pos, int length) {
        if (a1 == null && a2 != null)
            return false;
        if (a2 == null && a1 != null)
            return false;
        if (a1 == null)
            return true;
        if (a1.length < a1Pos + length)
            return false;
        if (a2.length < a2Pos + length)
            return false;
        for (int i = a1Pos, j = a2Pos; i < length; i++, j++) {
            if (a1[i] != a2[j])
                return false;
        }
        return true;
    }
}

Related

  1. byteArrayEquals(byte[] b1, byte[] b2)
  2. byteArrayEquals(final byte[] actual, final byte[] expected)
  3. byteArrayEquals(final byte[] lhs, final byte[] rhs)
  4. byteArraysEqual(byte[] b1, byte[] b2)