Compare Multidimensional Array in Android

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Compare Multidimensional Array in Android

Postby vivekkalady » Tue Dec 02, 2014 6:11 pm

First way to check equality is to use deepEquals:

Code: Select all

boolean check1 = Arrays.deepEquals(a2, a3);


Second way is to iterate the outer array explicitly:

Code: Select all

boolean check1 = true;
for (int i = 0; check1 && i < a2.length; ++i) {
    check1 = Arrays.equals(a2[i], a3[i]);
}


Thirst Way you can create a custom class called ArrayUtils like this

Code: Select all

import java.util.Arrays;

/**
 * Operations on multi-dimensional arrays.
 *
 * @author stephen harrison
 */
public class ArrayUtils {
    private ArrayUtils() {
        // Static methods only
    }

    public static <T> boolean equals(final T[][] a, final T[][] b) {
        if (a == b) {
            return true;
        }

        if (a == null || b == null) {
            return false;
        }

        if (a.length != b.length) {
            return false;
        }

        for (int i = 0; i < a.length; ++i) {
            if (!Arrays.equals(a[i], b[i])) {
                return false;
            }
        }

        return true;
    }

    public static <T> boolean equals(final T[][][] a, final T[][][] b) {
        if (a == b) {
            return true;
        }

        if (a == null || b == null) {
            return false;
        }

        if (a.length != b.length) {
            return false;
        }

        for (int i = 0; i < a.length; ++i) {
            if (!equals(a[i], b[i])) {
                return false;
            }
        }

        return true;
    }
}

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron