Java Array Capacity ensureCapacity(final T[] oldElements, final int requiredLength)

Here you can find the source of ensureCapacity(final T[] oldElements, final int requiredLength)

Description

Ensure an array has the required capacity.

License

Apache License

Parameter

Parameter Description
oldElements to ensure that are long enough.
requiredLength to ensure.
T type of the array.

Return

an array of the required length.

Declaration

public static <T> T[] ensureCapacity(final T[] oldElements, final int requiredLength) 

Method Source Code

//package com.java2s;
/*// www.  j  a v  a  2 s  .c om
 * Copyright 2014 - 2015 Real Logic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Arrays;

public class Main {
    /**
     * Ensure an array has the required capacity. Resizing only if needed.
     *
     * @param oldElements    to ensure that are long enough.
     * @param requiredLength to ensure.
     * @param <T>            type of the array.
     * @return               an array of the required length.
     */
    public static <T> T[] ensureCapacity(final T[] oldElements, final int requiredLength) {
        T[] result = oldElements;

        if (oldElements.length < requiredLength) {
            result = Arrays.copyOf(oldElements, requiredLength);
        }

        return result;
    }
}

Related

  1. ensureCapacity(byte array[], int capacity)
  2. ensureCapacity(byte[] bytes, int capacity)
  3. ensureCapacity(final double[] array, final int minCapacity)
  4. reduceCapacity(Object[] arrays)