Compare two arrays of data types for compatibility to each other. - Android java.lang

Android examples for java.lang:array compare

Description

Compare two arrays of data types for compatibility to each other.

Demo Code


//package com.java2s;
import android.support.annotation.NonNull;

public class Main {
    /** Compare two arrays of data types for compatibility to each other. */
    private static int compatible(@NonNull final Class<?>[] left,
            @NonNull final Class<?>[] right) {
        final int leftCount = left.length;
        final int rightCount = right.length;
        final int result = compare(leftCount, rightCount);

        if (result == 0) {
            for (int i = 0; i < leftCount; i++) {
                final Class<?> lType = boxing(left[i]);
                final Class<?> rType = boxing(right[i]);

                // check upcast/downcast compatibility
                if (!rType.isAssignableFrom(lType))
                    return -1;
            }// www.  ja va 2  s . co m
        }

        return result;
    }

    /**
     * Compares two {@code int} values.
     *
     * @return 0 if lhs = rhs, less than 0 if lhs &lt; rhs, and greater than 0 if lhs &gt; rhs.
     */
    private static int compare(final int lhs, final int rhs) {
        return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
    }

    /**
     * Change primitive types class to there 'boxed' compatible type.
     *
     * @param type check is provided type is primitive that can be converted to BOXED version.
     */
    public static Class<?> boxing(@NonNull final Class<?> type) {
        if (type.isPrimitive()) {
            if (boolean.class.equals(type))
                return Boolean.class;
            if (char.class.equals(type))
                return Character.class;
            if (byte.class.equals(type))
                return Byte.class;
            if (short.class.equals(type))
                return Short.class;
            if (int.class.equals(type))
                return Integer.class;
            if (long.class.equals(type))
                return Long.class;
            if (float.class.equals(type))
                return Float.class;
            if (double.class.equals(type))
                return Double.class;

            throw new AssertionError(
                    "Not implemented! primitive to 'boxed' convert failed for type:"
                            + type);
        }

        return type;
    }
}

Related Tutorials