集册 Java实例教程 如果对象是数组实例并且它们的每个元素也通过equals进行比较,则返回true。

如果对象是数组实例并且它们的每个元素也通过equals进行比较,则返回true。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

588
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
如果对象是数组实例并且它们的每个元素也通过equals进行比较,则返回true。


//package com.nowjava;


public class Main {/**时代Java**/

    public static void main(String[] argv) {

        Object value = "nowjava.com";

        Object otherValue = "nowjava.com";

        System.out.println(arraysAreEqual(value, otherValue));

    }


    /**

     * Returns true if the objects are array instances and each of their elements compares

     * via equals as well.

     * 

     * @param value Object

     * @param otherValue Object

     * @return boolean

     */

    public static final boolean arraysAreEqual(Object value,

            Object otherValue) {

        if (value instanceof Object[]) {
        /*
        时代Java公众号 - nowjava.com 提供
        */

            if (otherValue instanceof Object[])

                return valuesAreTransitivelyEqual((Object[]) value,

                        (Object[]) otherValue);

            return false;

        }

        return false;

    }


    /**

     * Returns whether the arrays are equal by examining each of their elements, even if they are

     * arrays themselves.

     * 

     * @param thisArray Object[]

     * @param thatArray Object[]

     * @return boolean

     */

    public static final boolean valuesAreTransitivelyEqual(

            Object[] thisArray, Object[] thatArray) {

        if (thisArray == thatArray)

            return true;

        if ((thisArray == null) || (thatArray == null))

            return false;

        if (thisArray.length != thatArray.length)

            return false;

        for (int i = 0; i < thisArray.length; i++) {

            if (!areEqual(thisArray[i], thatArray[i]))

                return false; // recurse if req'd

        }

        return true;

    }


    /**

     * A comprehensive isEqual method that handles nulls and arrays safely.

     * 

     * @param value Object

     * @param otherValue Object

     * @return boolean

     */

    public static final boolean areEqual(Object value, Object otherValue) {

   
展开阅读全文