add Item to array by index - Android java.lang

Android examples for java.lang:array

Description

add Item to array by index

Demo Code


//package com.java2s;

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;//from   w w w .j a v a  2 s.co  m

        @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;
    }
}

Related Tutorials