Removes the items array elements from the end of the array. - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

Removes the items array elements from the end of the array.

Demo Code


//package com.java2s;

import java.lang.reflect.Array;

public class Main {
    /**//from w w  w . ja v  a2s .  c  om
     * Removes the <code>items</code> array elements from the end of the array.
     * @param array The array to truncate
     * @param items The number of items to truncate from the end of the array
     * @return The truncated array.
     */
    public static <E> E[] truncate(E[] array, int items) {
        if (items == 0)
            return array;
        if (array == null)
            throw new RuntimeException("Array was null");
        if (items < 0)
            throw new RuntimeException("Item count was < 0");
        if (items >= array.length)
            return (E[]) Array.newInstance(array.getClass()
                    .getComponentType(), 0);
        int diff = array.length - items;
        E[] newArray = (E[]) Array.newInstance(array.getClass()
                .getComponentType(), diff);
        System.arraycopy(array, 0, newArray, 0, diff);
        return newArray;
    }
}

Related Tutorials