Join two arrays to a new array. - Android java.lang

Android examples for java.lang:array join

Description

Join two arrays to a new array.

Demo Code

import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main{

    /**/*from   w ww . j a  v  a 2 s .  c  o  m*/
     * Join two arrays to a new array.
     * 
     * @param a1
     * @param a2
     * @return
     */
    public static byte[] join(byte[] a1, byte[] a2) {
        byte[] result = new byte[a1.length + a2.length];
        System.arraycopy(a1, 0, result, 0, a1.length);
        System.arraycopy(a2, 0, result, a1.length, a2.length);
        return result;
    }
    /**
     * Join two or more arrays a new array.
     * 
     * @param a
     * @return
     */
    public static byte[] join(byte[]... a) {
        if (a == null) {
            return null;
        }
        int count = a.length;
        // one array.
        if (count == 1) {
            return a[0];
        }
        // two or more arrays.
        int totalLength = 0;
        for (int i = 0; i < count; i++) {
            totalLength += a[i].length;
        }
        byte[] result = new byte[totalLength];
        int p = 0;
        for (int i = 0; i < a.length; i++) {
            System.arraycopy(a[i], 0, result, p, a[i].length);
            p += a[i].length;
        }
        return result;
    }

}

Related Tutorials