Compares the two specified arrays. - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Compares the two specified arrays.

Demo Code


//package com.java2s;
import java.lang.reflect.Array;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object array1 = "java2s.com";
        Object array2 = "java2s.com";
        System.out.println(areArraysEqual(array1, array2));
    }/*w ww. j  a v a 2  s.  co m*/

    /**
     * Compares the two specified arrays. If both passed objects are
     * <code>null</code>, <code>true</code> is returned. If both passed 
     * objects are not arrays, they are compared using <code>equals</code>. 
     * Otherwise all array elements are compared using <code>equals</code>.
     * This method does not handle multidimensional arrays, i.e. if an
     * array contains another array, comparison is based on identity.
     * @param array1 the first array
     * @param array2 the second array
     * @return <code>true</code> if the arrays are equal, <code>false</code>
     *         otherwise
     */
    public static boolean areArraysEqual(Object array1, Object array2) {
        if (null == array1 && null == array2)
            return true;
        if (null == array1 || null == array2)
            return false;
        if (!array1.getClass().isArray() && !array2.getClass().isArray())
            return array1.equals(array2);
        if (!array1.getClass().isArray() || !array2.getClass().isArray())
            return false;
        int length1 = Array.getLength(array1);
        int length2 = Array.getLength(array2);
        if (length1 != length2)
            return false;
        for (int ii = 0; ii < length1; ii++) {
            Object value1 = Array.get(array1, ii);
            Object value2 = Array.get(array2, ii);
            if (null != value1 && !value1.equals(value2))
                return false;
            if (null == value1 && null != value2)
                return false;
        }
        return true;
    }
}

Related Tutorials