java将多个array数据合并,并完美实现null安全

墨色 4月前 ⋅ 254 阅读

嗯,直接上代码吧


public static <T> T[] concat(T[] first, T[]... rest) {
    int totalLength = 0;
    T[] result = null, temp = null;
    if (first != null && first.length > 0) {
        totalLength = first.length;
    }
    if (totalLength == 0) {
        for (T[] array : rest) {
            if (array != null && array.length > 0) {
                if (totalLength == 0) {
                    temp = array;
                    totalLength += array.length;
                } else {
                    temp = concat(temp, array);
                }
            }
        }
        result = temp;
    } else {
        for (T[] array : rest) {
            if (array != null && array.length > 0) {
                totalLength += array.length;
            }
        }
        if (totalLength != 0) {
            result = Arrays.copyOf(first, totalLength);
            int offset = first.length;
            for (T[] array : rest) {
                if (array != null && array.length > 0) {
                    System.arraycopy(array, 0, result, offset, array.length);
                    offset += array.length;
                }
            }
        }
    }
    return result;
}

public static <T> T[] concat(T[] first, T[] second) {
    T[] result = Arrays.copyOf(first, first.length + second.length);
    System.arraycopy(second, 0, result, first.length, second.length);
    return result;
}

全部评论: 0

    我有话说: