集册 Java实例教程 将第二个数组中的值添加到第一个数组,重用第一个数组,如果可能的话,结果将被扩展以适合数组中数组元素的最大数量。

将第二个数组中的值添加到第一个数组,重用第一个数组,如果可能的话,结果将被扩展以适合数组中数组元素的最大数量。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

369
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将第二个数组中的值添加到第一个数组中,并在可能的情况下重用第一个数组。结果将扩展为适合任一数组中最大数组元素的数量
/** 时代Java - nowjava.com 提 供 **/


//package com.nowjava;

import java.util.Arrays;


public class Main {

    public static void main(String[] argv) throws Exception {

        int[] first = new int[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };

        int[] second = new int[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };

        System.out.println(java.util.Arrays.toString(add(first, second)));

    }


    private static int[] EMPTY_INT_ARRAY = new int[0];

    private static float[] EMPTY_FLOAT_ARRAY = new float[0];


    /**

     * Adds the values from the second array to the first,

     * reusing the first array if possible

     * The result will be expanded to fit the maximum number of array elements in either array

     */

    public static int[] add(int[] first, int[] second) {

        if (first == null && second == null)

            return EMPTY_INT_ARRAY;

        if (second == null)

            return first;

        if (first == null)
        /* 
         来自 
        *时代Java公众号 - N o w J a  v a . c o m*/

            return Arrays.copyOf(second, second.length);

        if (first.length < second.length) {

            first = Arrays.copyOf(first, second.length);

        }

        int nOverlap = Math.min(first.length, second.length);

        for (int i = 0; i < nOverlap; i++) {

            first[i] += second[i];

        }

        return first;

    }


    /**

     * Adds the values from the second array to the first,

     * reusing the first array if possible

     * The result will be expanded to fit the maximum number of array elements in either array

     */

    public static float[] add(float[] first, float[] second) {

        if (first == null && second == null)

            return EMPTY_FLOAT_ARRAY;

        if (second == null)

            return first;

        if (first == null)

            return Arrays.copyOf(second, second.length);

        if (first.length < second.length) {

            first = Arrays.copyOf(first, second.length);

        }

        int nOverlap = Math.min(first.length, second.length);

        for (int i = 0; i < nOverlap; i++) {

            first[i] += second[i];

        }

        return first;

    }


    
展开阅读全文