简介

java Arrays中定义了如下几种equals方法,用来对比判断数组是否相等

  • equals(boolean[], boolean[])
  • equals(byte[], boolean[])
  • equals(char[], boolean[])
  • equals(double[], boolean[])
  • equals(float[], boolean[])
  • equals(short[], boolean[])
  • equals(int[], boolean[])
  • equals(long[], boolean[])
  • equals(Object[], boolean[])

源码

每一个方法里的源码实现基本都差不多,我们看下equals(int[], boolean[])的源码实现

代码很简单,若两个数组的长度相等,且每一个位置的元素也相等,则认为这两个数组相等

/**
 * Returns <tt>true</tt> if the two specified arrays of ints are
 * <i>equal</i> to one another.  Two arrays are considered equal if both
 * arrays contain the same number of elements, and all corresponding pairs
 * of elements in the two arrays are equal.  In other words, two arrays
 * are equal if they contain the same elements in the same order.  Also,
 * two array references are considered equal if both are <tt>null</tt>.<p>
 *
 * @param a one array to be tested for equality
 * @param a2 the other array to be tested for equality
 * @return <tt>true</tt> if the two arrays are equal
 */
public static boolean equals(int[] a, int[] a2) {
    if (a==a2)
        return true;
    if (a==null || a2==null)
        return false;

    int length = a.length;
    if (a2.length != length)
        return false;

    for (int i=0; i<length; i++)
        if (a[i] != a2[i])
            return false;

    return true;
}

使用

public class Test {
    public static void main(String[] args) {
        int[] array1 = new int[]{1, 2, 3};
        int[] array2 = array1;
        int[] array3 = new int[]{1, 2, 3};
        int[] array4 = new int[]{4, 5, 6};
        if(Arrays.equals(array1, array2)) {
            System.out.println("array1等于array2");
        } else {
            System.out.println("array1不等于array2");
        }
        if(Arrays.equals(array1, array3)) {
            System.out.println("array1等于array3");
        } else {
            System.out.println("array1不等于array3");
        }
        if(Arrays.equals(array1, array4)) {
            System.out.println("array1等于array4");
        } else {
            System.out.println("array1不等于array4");
        }
    }
}

 运行结果如下

array1等于array2
array1等于array3
array1不等于array4

 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐