Adds a padding to the given array, such that a new array with the given length is generated. - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

Adds a padding to the given array, such that a new array with the given length is generated.

Demo Code


//package com.java2s;

import java.util.Arrays;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] array = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        byte value = 2;
        int newLength = 2;
        System.out.println(java.util.Arrays.toString(padArray(array, value,
                newLength)));//from  ww  w  .  j  a  v a 2 s  . co  m
    }

    /**
     * Adds a padding to the given array, such that a new array with the given
     * length is generated.
     * 
     * @param array
     *            the array to be padded.
     * @param value
     *            the padding value.
     * @param newLength
     *            the new length of the padded array.
     * @return the array padded with the given value.
     */
    public static byte[] padArray(byte[] array, byte value, int newLength) {
        int length = array.length;
        int paddingLength = newLength - length;

        if (paddingLength < 1) {
            return array;
        } else {
            byte[] padding = new byte[paddingLength];
            Arrays.fill(padding, value);

            return concatenate(array, padding);
        }

    }

    /**
     * Concatenates two byte arrays.
     * 
     * @param a
     *            the first array.
     * @param b
     *            the second array.
     * @return the concatenated array.
     */
    public static byte[] concatenate(byte[] a, byte[] b) {
        int lengthA = a.length;
        int lengthB = b.length;

        byte[] concat = new byte[lengthA + lengthB];

        System.arraycopy(a, 0, concat, 0, lengthA);
        System.arraycopy(b, 0, concat, lengthA, lengthB);

        return concat;
    }
}

Related Tutorials