Generic method to add Item to an array - Android java.lang

Android examples for java.lang:array

Description

Generic method to add Item to an array

Demo Code

import android.support.annotation.Nullable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

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;/*  www.j  ava  2s .c  om*/

        @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