要比较两个字节数组,请使用Arrays.equals()方法。在这里,我们已经声明并初始化了总共4个数组。
byte[] arr1 = new byte[] { 11, 13, 30, 45, 77, 89 }; byte[] arr2 = new byte[] { 12, 13, 34, 87, 99, 33}; byte[] arr3 = new byte[] { 11, 13, 30, 45, 77, 89 }; byte[] arr4 = new byte[] { 13, 16, 56, 78, 98, 99 };
现在,使用Arrays.equals()方法,我们将比较两个数组。
Arrays.equals(arr1, arr2);
同样,其他数组将被一个一个地比较。
让我们看一下比较两个字节数组的完整示例。
import java.util.*; public class Demo { public static void main(String[] args) { byte[] arr1 = new byte[] { 11, 13, 30, 45, 77, 89 }; byte[] arr2 = new byte[] { 12, 13, 34, 87, 99, 33}; byte[] arr3 = new byte[] { 11, 13, 30, 45, 77, 89 }; byte[] arr4 = new byte[] { 13, 16, 56, 78, 98, 99 }; System.out.println("Array1 is equal to Array2 = "+Arrays.equals(arr1, arr2)); System.out.println("Array1 is equal to Array3 = "+Arrays.equals(arr1, arr3)); System.out.println("Array1 is equal to Array4 = "+Arrays.equals(arr1, arr4)); System.out.println("Array2 is equal to Array3 = "+Arrays.equals(arr2, arr3)); } }
输出结果
Array1 is equal to Array2 = false Array1 is equal to Array3 = true Array1 is equal to Array4 = false Array2 is equal to Array3 = false