Arrays.equals ???
От: Cheblin2 Китай https://github.com/cheblin
Дата: 05.04.21 09:09
Оценка: -1 :)
вынужден переписывать встроенный в Java функционал

имеем Arrays.equals
/**
     * Returns {@code true} if the two specified arrays of Objects are
     * <i>equal</i> to one another.
     *
     * <p>Two arrays are considered equal if both arrays contain the same number
     * of elements, and all corresponding pairs of elements in the two arrays
     * are equal.  In other words, the two arrays are equal if they contain the
     * same elements in the same order.  Also, two array references are
     * considered equal if both are {@code null}.
     *
     * <p>Two objects {@code e1} and {@code e2} are considered <i>equal</i> if,
     * given the specified comparator, {@code cmp.compare(e1, e2) == 0}.
     *
     * @param a one array to be tested for equality
     * @param a2 the other array to be tested for equality
     * @param cmp the comparator to compare array elements
     * @param <T> the type of array elements
     * @return {@code true} if the two arrays are equal
     * @throws NullPointerException if the comparator is {@code null}
     * @since 9
     */

 public static <T> boolean equals(T[] a, T[] a2, Comparator<? super T> cmp) {
        Objects.requireNonNull(cmp);
        if (a==a2)
            return true;
        if (a==null || a2==null)
            return false;

        int length = a.length;
        if (a2.length != length)
            return false;

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

        return true;
    }


естественно падает если какой элемент == null

почему нельзя было сделать вот так?

 public static <T> boolean equals(T[] a, T[] a2, Comparator<? super T> cmp) {
        Objects.requireNonNull(cmp);
        if (a==a2)
            return true;
        if (a==null || a2==null)
            return false;

        int length = a.length;
        if (a2.length != length)
            return false;

        for (int i=0; i<length; i++) {
            if ( a[i] != a2[i] && cmp.compare(a[i], a2[i]) != 0)// <<<<        a[i] != a2[i] &&
                return false;
        }

        return true;
    }


это бесит
Отредактировано 05.04.2021 9:14 Cheblin2 . Предыдущая версия . Еще …
Отредактировано 05.04.2021 9:11 Cheblin2 . Предыдущая версия .
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.