Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Array;

public class Main {
    public static <T extends Object> T[] addItem(T[] array, T item, int index) {
        int size = array == null ? 0 : array.length;

        if (index < 0 || index > size)
            index = size;

        @SuppressWarnings("unchecked")
        T[] result = (T[]) Array.newInstance(item.getClass(), size + 1);

        if (index > 0 && array != null)
            System.arraycopy(array, 0, result, 0, index);

        result[index] = item;

        if (index < result.length - 1 && array != null)
            System.arraycopy(array, index, result, index + 1, array.length - index);

        return result;
    }
}