Concatenate the given String arrays into one, with overlapping array elements included twice. - Java java.lang

Java examples for java.lang:String Array

Description

Concatenate the given String arrays into one, with overlapping array elements included twice.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] array1 = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        String[] array2 = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(java.util.Arrays
                .toString(concatenateStringArrays(array1, array2)));
    }//from w  w w  .ja v a 2  s.c o  m

    /**
     * Concatenate the given String arrays into one, with overlapping array elements included twice. <p>The
     * order of elements in the original arrays is preserved.
     *
     * @param array1
     *            the first array (can be <code>null</code>)
     * @param array2
     *            the second array (can be <code>null</code>)
     * @return the new array (<code>null</code> if both given arrays were <code>null</code>)
     */
    public static String[] concatenateStringArrays(final String[] array1,
            final String[] array2) {

        // if (ObjectUtils.isEmpty(array1)) {
        if (array1.length == 0)
            return array2;
        // if (ObjectUtils.isEmpty(array2)) {
        if (array2.length == 0)
            return array1;
        final String[] newArr = new String[array1.length + array2.length];
        System.arraycopy(array1, 0, newArr, 0, array1.length);
        System.arraycopy(array2, 0, newArr, array1.length, array2.length);
        return newArr;
    }
}

Related Tutorials