集册 Java实例教程 将元素追加到数组

将元素追加到数组

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

483
将元素追加到数组


//package com.nowjava;

import java.lang.reflect.Array;

/*
N o  w  J a v a . c o m - 时  代  Java 提 供
*/

public class Main {


    public static <T> T[] append(T[] buffer, T newElement) {

        T[] t = resize(buffer, buffer.length + 1, newElement.getClass());

        t[buffer.length] = newElement;

        return t;

    }


    public static <T> T[] resize(T[] buffer, int newSize,

            Class<?> componentType) {

        T[] newArray = newArray(componentType, newSize);

        System.arraycopy(buffer, 0, newArray, 0,

                buffer.length >= newSize ? newSize : buffer.length);

        return newArray;

    }


    public static <T> T[] resize(T[] buffer, int newSize) {

        return resize(buffer, newSize, buffer.getClass().getComponentType());//from n  o  w  j  a  v  a . c o m

    }


    @SuppressWarnings("unchecked")

    
展开阅读全文