add String Item To String Array - Java java.lang

Java examples for java.lang:String Array

Description

add String Item To String Array

Demo Code

/*/*from   w ww  .j av  a 2 s.  c  o m*/
 * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */
//package com.java2s;
import java.lang.reflect.Array;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] array = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        String item = "java2s.com";
        System.out.println(java.util.Arrays.toString(addItemToStringArray(
                array, item)));
    }

    public static String[] addItemToStringArray(String[] array, String item) {
        String[] array2 = new String[] { item };
        if (array == null) {
            return array2;
        }

        return arrayMerge(array, array2);
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] arrayMerge(T[]... arrays) {
        // Determine required size of new array
        int count = 0;
        for (T[] array : arrays) {
            count += array.length;
        }

        if (count == 0) {
            return (T[]) Array.newInstance(arrays.getClass()
                    .getComponentType().getComponentType(), 0);
        }

        // create new array of required class
        T[] mergedArray = (T[]) Array.newInstance(arrays[0][0].getClass(),
                count);

        // Merge each array into new array
        int start = 0;
        for (T[] array : arrays) {
            System.arraycopy(array, 0, mergedArray, start, array.length);
            start += array.length;
        }

        return (T[]) mergedArray;
    }
}

Related Tutorials