Append the given String to the given String array, returning a new array consisting of the input array contents plus the given String. - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

Append the given String to the given String array, returning a new array consisting of the input array contents plus the given String.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] array = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        String str = "java2s.com";
        System.out.println(java.util.Arrays.toString(addStringToArray(
                array, str)));//  w w w . j a  v  a2 s  .  co m
    }

    /**
     * Append the given String to the given String array, returning a new array consisting of the input array
     * contents plus the given String.
     *
     * @param array
     *            the array to append to (can be <code>null</code>)
     * @param str
     *            the String to append
     * @return the new array (never <code>null</code>)
     */
    public static String[] addStringToArray(final String[] array,
            final String str) {

        // if (ObjectUtils.isEmpty(array)) {
        if (array.length == 0)
            return new String[] { str };

        final String[] newArr = new String[array.length + 1];
        System.arraycopy(array, 0, newArr, 0, array.length);
        newArr[array.length] = str;
        return newArr;
    }
}

Related Tutorials