Compares the two Objects for equality. - Java java.lang

Java examples for java.lang:Object

Description

Compares the two Objects for equality.

Demo Code

/*/* w w w.j a  v  a  2  s .  c  om*/
 * Copyright (c) 2015-2016 QuartzDesk.com.
 * Licensed under the MIT license (https://opensource.org/licenses/MIT).
 */
//package com.java2s;

import java.lang.reflect.Array;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object o1 = "java2s.com";
        Object o2 = "java2s.com";
        System.out.println(safeEquals(o1, o2));
    }

    /**
     * Compares the two Objects for equality. This method returns true if both Objects are null,
     * or they are equal according to the {@link Object#equals(Object)} method, false otherwise.
     * In case the specified objects are arrays, this method performs deep equality check of all
     * array elements.
     *
     * @param o1 the first object.
     * @param o2 the second object.
     * @return true if both Objects are equal, false otherwise.
     */
    public static boolean safeEquals(Object o1, Object o2) {
        if (o1 == o2)
            return true;

        if (o1 != null && o2 == null)
            return false;

        if (o1 == null) // o2 != null
            return false;

        if (o1.getClass().isArray() && o2.getClass().isArray()) {
            int length1 = Array.getLength(o1);
            int length2 = Array.getLength(o2);

            // array lengths must be equal
            if (length1 != length2)
                return false;

            // array component types must be equal
            if (!o1.getClass().getComponentType()
                    .equals(o2.getClass().getComponentType()))
                return false;

            // individual elements must be equal
            for (int i = 0; i < length1; i++) {
                if (!safeEquals(Array.get(o1, i), Array.get(o2, i)))
                    return false;
            }
            return true;
        }

        return o1.equals(o2);
    }
}

Related Tutorials