集册 Java实例教程 从数组末尾移除items数组元素。

从数组末尾移除items数组元素。

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

396
从数组的末尾删除items数组元素。


//package com.nowjava;


import java.lang.reflect.Array;/* 来自 n o w j a v a . c o m*/


public class Main {

    /**

     * 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[]) 
展开阅读全文