<p>I need to concatenate two <code>String</code> arrays in Java.</p>
<pre><code>void f(String[] first, String[] second) {
    String[] both = ???
}
</code></pre>
<p>Which is the easiest way to do this?</p>

[{'answer_id': 80503, 'author': 'jeannicolas', 'author_id': 14981, 'author_profile': 'https://Stackoverflow.com/users/14981', 'pm_score': 10, 'selected': False, 'text': '<p>Here\'s a simple method that will concatenate two arrays and return the result:</p>\n\n<pre><code>public &lt;T&gt; T[] concatenate(T[] a, T[] b) {\n    int aLen = a.length;\n    int bLen = b.length;\n\n    @SuppressWarnings("unchecked")\n    T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);\n    System.arraycopy(a, 0, c, 0, aLen);\n    System.arraycopy(b, 0, c, aLen, bLen);\n\n    return c;\n}\n</code></pre>\n\n<p>Note that it will not work with primitive data types, only with object types.</p>\n\n<p>The following slightly more complicated version works with both object and primitive arrays. It does this by using <code>T</code> instead of <code>T[]</code> as the argument type.</p>\n\n<p>It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.</p>\n\n<pre><code>public static &lt;T&gt; T concatenate(T a, T b) {\n    if (!a.getClass().isArray() || !b.getClass().isArray()) {\n        throw new IllegalArgumentException();\n    }\n\n    Class&lt;?&gt; resCompType;\n    Class&lt;?&gt; aCompType = a.getClass().getComponentType();\n    Class&lt;?&gt; bCompType = b.getClass().getComponentType();\n\n    if (aCompType.isAssignableFrom(bCompType)) {\n        resCompType = aCompType;\n    } else if (bCompType.isAssignableFrom(aCompType)) {\n        resCompType = bCompType;\n    } else {\n        throw new IllegalArgumentException();\n    }\n\n    int aLen = Array.getLength(a);\n    int bLen = Array.getLength(b);\n\n    @SuppressWarnings("unchecked")\n    T result = (T) Array.newInstance(resCompType, aLen + bLen);\n    System.arraycopy(a, 0, result, 0, aLen);\n    System.arraycopy(b, 0, result, aLen, bLen);        \n\n    return result;\n}\n</code></pre>\n\n<p>Here is an example:</p>\n\n<pre><code>Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));\nAssert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));\n</code></pre>\n'}, {'answer_id': 80559, 'author': 'Antti Kissaniemi', 'author_id': 2948, 'author_profile': 'https://Stackoverflow.com/users/2948', 'pm_score': 10, 'selected': False, 'text': '<p>I found a one-line solution from the good old Apache Commons Lang library.<br> <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#addAll%28T%5B%5D,%20T...%29" rel="noreferrer"><code>ArrayUtils.addAll(T[], T...)</code></a></p>\n\n<p>Code:</p>\n\n<pre><code>String[] both = ArrayUtils.addAll(first, second);\n</code></pre>\n'}, {'answer_id': 80621, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 5, 'selected': False, 'text': '<p>The <a href="http://functionaljava.org" rel="noreferrer">Functional Java</a> library has an array wrapper class that equips arrays with handy methods like concatenation.</p>\n\n<pre><code>import static fj.data.Array.array;\n</code></pre>\n\n<p>...and then</p>\n\n<pre><code>Array&lt;String&gt; both = array(first).append(array(second));\n</code></pre>\n\n<p>To get the unwrapped array back out, call</p>\n\n<pre><code>String[] s = both.array();\n</code></pre>\n'}, {'answer_id': 80977, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Using only Javas own API:</p>\n\n<pre><code>\nString[] join(String[]... arrays) {\n  // calculate size of target array\n  int size = 0;\n  for (String[] array : arrays) {\n    size += array.length;\n  }\n\n  // create list of appropriate size\n  java.util.List list = new java.util.ArrayList(size);\n\n  // add arrays\n  for (String[] array : arrays) {\n    list.addAll(java.util.Arrays.asList(array));\n  }\n\n  // create and return final array\n  return list.toArray(new String[size]);\n}\n</code></pre>\n\n<p>Now, this code ist not the most efficient, but it relies only on standard java classes and is easy to understand. It works for any number of String[] (even zero arrays).</p>\n'}, {'answer_id': 85216, 'author': 'volley', 'author_id': 13905, 'author_profile': 'https://Stackoverflow.com/users/13905', 'pm_score': 4, 'selected': False, 'text': '<p>Here\'s an adaptation of silvertab\'s solution, with generics retrofitted:</p>\n\n<pre><code>static &lt;T&gt; T[] concat(T[] a, T[] b) {\n    final int alen = a.length;\n    final int blen = b.length;\n    final T[] result = (T[]) java.lang.reflect.Array.\n            newInstance(a.getClass().getComponentType(), alen + blen);\n    System.arraycopy(a, 0, result, 0, alen);\n    System.arraycopy(b, 0, result, alen, blen);\n    return result;\n}\n</code></pre>\n\n<p>NOTE: See <a href="https://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java/784842#784842">Joachim\'s answer</a> for a Java 6 solution. Not only does it eliminate the warning; it\'s also shorter, more efficient and easier to read!</p>\n'}, {'answer_id': 85266, 'author': 'volley', 'author_id': 13905, 'author_profile': 'https://Stackoverflow.com/users/13905', 'pm_score': 5, 'selected': False, 'text': "<p>I've recently fought problems with excessive memory rotation. If a and/or b are known to be commonly empty, here is another adaption of silvertab's code (generified too):</p>\n\n<pre><code>private static &lt;T&gt; T[] concatOrReturnSame(T[] a, T[] b) {\n    final int alen = a.length;\n    final int blen = b.length;\n    if (alen == 0) {\n        return b;\n    }\n    if (blen == 0) {\n        return a;\n    }\n    final T[] result = (T[]) java.lang.reflect.Array.\n            newInstance(a.getClass().getComponentType(), alen + blen);\n    System.arraycopy(a, 0, result, 0, alen);\n    System.arraycopy(b, 0, result, alen, blen);\n    return result;\n}\n</code></pre>\n\n<p>Edit: A previous version of this post stated that array re-usage like this shall be clearly documented. As Maarten points out in the comments it would in general be better to just remove the if statements, thus voiding the need for having documentation. But then again, those if statements were the whole point of this particular optimization in the first place. I'll leave this answer here, but be wary!</p>\n"}, {'answer_id': 96892, 'author': 'Fabian Steeg', 'author_id': 18154, 'author_profile': 'https://Stackoverflow.com/users/18154', 'pm_score': 6, 'selected': False, 'text': '<p>Using the Java API:</p>\n\n<pre><code>String[] f(String[] first, String[] second) {\n    List&lt;String&gt; both = new ArrayList&lt;String&gt;(first.length + second.length);\n    Collections.addAll(both, first);\n    Collections.addAll(both, second);\n    return both.toArray(new String[both.size()]);\n}\n</code></pre>\n'}, {'answer_id': 135237, 'author': 'Bob Cross', 'author_id': 5812, 'author_profile': 'https://Stackoverflow.com/users/5812', 'pm_score': 2, 'selected': False, 'text': "<p>If you'd like to work with ArrayLists in the solution, you can try this:</p>\n\n<pre><code>public final String [] f(final String [] first, final String [] second) {\n    // Assuming non-null for brevity.\n    final ArrayList&lt;String&gt; resultList = new ArrayList&lt;String&gt;(Arrays.asList(first));\n    resultList.addAll(new ArrayList&lt;String&gt;(Arrays.asList(second)));\n    return resultList.toArray(new String [resultList.size()]);\n}\n</code></pre>\n"}, {'answer_id': 707558, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I tested below code and worked ok</p>\n\n<p>Also I\'m using library: org.apache.commons.lang.ArrayUtils</p>\n\n<pre><code>public void testConcatArrayString(){\n    String[] a = null;\n    String[] b = null;\n    String[] c = null;\n    a = new String[] {"1","2","3","4","5"};\n    b = new String[] {"A","B","C","D","E"};\n\n    c = (String[]) ArrayUtils.addAll(a, b);\n    if(c!=null){\n        for(int i=0; i&lt;c.length; i++){\n            System.out.println("c[" + (i+1) + "] = " + c[i]);\n        }\n    }\n}\n</code></pre>\n\n<p>Regards</p>\n'}, {'answer_id': 784813, 'author': 'glue', 'author_id': 94685, 'author_profile': 'https://Stackoverflow.com/users/94685', 'pm_score': 3, 'selected': False, 'text': '<p>This works, but you need to insert your own error checking.</p>\n\n<pre><code>public class StringConcatenate {\n\n    public static void main(String[] args){\n\n        // Create two arrays to concatenate and one array to hold both\n        String[] arr1 = new String[]{"s","t","r","i","n","g"};\n        String[] arr2 = new String[]{"s","t","r","i","n","g"};\n        String[] arrBoth = new String[arr1.length+arr2.length];\n\n        // Copy elements from first array into first part of new array\n        for(int i = 0; i &lt; arr1.length; i++){\n            arrBoth[i] = arr1[i];\n        }\n\n        // Copy elements from second array into last part of new array\n        for(int j = arr1.length;j &lt; arrBoth.length;j++){\n            arrBoth[j] = arr2[j-arr1.length];\n        }\n\n        // Print result\n        for(int k = 0; k &lt; arrBoth.length; k++){\n            System.out.print(arrBoth[k]);\n        }\n\n        // Additional line to make your terminal look better at completion!\n        System.out.println();\n    }\n}\n</code></pre>\n\n<p>\nIt\'s probably not the most efficient, but it doesn\'t rely on anything other than Java\'s own API.</p>\n'}, {'answer_id': 784842, 'author': 'Joachim Sauer', 'author_id': 40342, 'author_profile': 'https://Stackoverflow.com/users/40342', 'pm_score': 9, 'selected': False, 'text': '<p>It\'s possible to write a fully generic version that can even be extended to concatenate any number of arrays. This versions require Java 6, as they use <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf%28T[],%20int%29" rel="noreferrer"><code>Arrays.copyOf()</code></a></p>\n\n<p>Both versions avoid creating any intermediary <code>List</code> objects and use <code>System.arraycopy()</code> to ensure that copying large arrays is as fast as possible.</p>\n\n<p>For two arrays it looks like this:</p>\n\n<pre><code>public static &lt;T&gt; T[] concat(T[] first, T[] second) {\n  T[] result = Arrays.copyOf(first, first.length + second.length);\n  System.arraycopy(second, 0, result, first.length, second.length);\n  return result;\n}\n</code></pre>\n\n<p>And for a arbitrary number of arrays (>= 1) it looks like this:</p>\n\n<pre><code>public static &lt;T&gt; T[] concatAll(T[] first, T[]... rest) {\n  int totalLength = first.length;\n  for (T[] array : rest) {\n    totalLength += array.length;\n  }\n  T[] result = Arrays.copyOf(first, totalLength);\n  int offset = first.length;\n  for (T[] array : rest) {\n    System.arraycopy(array, 0, result, offset, array.length);\n    offset += array.length;\n  }\n  return result;\n}\n</code></pre>\n'}, {'answer_id': 786450, 'author': 'MetroidFan2002', 'author_id': 8026, 'author_profile': 'https://Stackoverflow.com/users/8026', 'pm_score': 2, 'selected': False, 'text': '<p>An easy, but inefficient, way to do this (generics not included):</p>\n\n<pre><code>ArrayList baseArray = new ArrayList(Arrays.asList(array1));\nbaseArray.addAll(Arrays.asList(array2));\nString concatenated[] = (String []) baseArray.toArray(new String[baseArray.size()]);\n</code></pre>\n'}, {'answer_id': 1012285, 'author': 'Damo', 'author_id': 2955, 'author_profile': 'https://Stackoverflow.com/users/2955', 'pm_score': 3, 'selected': False, 'text': '<p>A simple variation allowing the joining of more than one array:</p>\n\n<pre><code>public static String[] join(String[]...arrays) {\n\n    final List&lt;String&gt; output = new ArrayList&lt;String&gt;();\n\n    for(String[] array : arrays) {\n        output.addAll(Arrays.asList(array));\n    }\n\n    return output.toArray(new String[output.size()]);\n}\n</code></pre>\n'}, {'answer_id': 1012309, 'author': 'Damo', 'author_id': 2955, 'author_profile': 'https://Stackoverflow.com/users/2955', 'pm_score': 2, 'selected': False, 'text': '<p>A type independent variation (UPDATED - thanks to Volley for instantiating T):</p>\n\n<pre><code>@SuppressWarnings("unchecked")\npublic static &lt;T&gt; T[] join(T[]...arrays) {\n\n    final List&lt;T&gt; output = new ArrayList&lt;T&gt;();\n\n    for(T[] array : arrays) {\n        output.addAll(Arrays.asList(array));\n    }\n\n    return output.toArray((T[])Array.newInstance(\n        arrays[0].getClass().getComponentType(), output.size()));\n}\n</code></pre>\n'}, {'answer_id': 4552278, 'author': 'Sujay', 'author_id': 556856, 'author_profile': 'https://Stackoverflow.com/users/556856', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public String[] concat(String[]... arrays)\n{\n    int length = 0;\n    for (String[] array : arrays) {\n        length += array.length;\n    }\n    String[] result = new String[length];\n    int destPos = 0;\n    for (String[] array : arrays) {\n        System.arraycopy(array, 0, result, destPos, array.length);\n        destPos += array.length;\n    }\n    return result;\n}\n</code></pre>\n'}, {'answer_id': 4574691, 'author': 'Doug', 'author_id': 543770, 'author_profile': 'https://Stackoverflow.com/users/543770', 'pm_score': 2, 'selected': False, 'text': "<p>Another one based on SilverTab's suggestion, but made to support x number of arguments and not require Java 6. It is also not generic, but I'm sure it could be made generic.</p>\n\n<pre><code>private byte[] concat(byte[]... args)\n{\n    int fulllength = 0;\n    for (byte[] arrItem : args)\n    {\n        fulllength += arrItem.length;\n    }\n    byte[] retArray = new byte[fulllength];\n    int start = 0;\n    for (byte[] arrItem : args)\n    {\n        System.arraycopy(arrItem, 0, retArray, start, arrItem.length);\n        start += arrItem.length;\n    }\n    return retArray;\n}\n</code></pre>\n"}, {'answer_id': 5247896, 'author': 'KARASZI István', 'author_id': 221213, 'author_profile': 'https://Stackoverflow.com/users/221213', 'pm_score': 8, 'selected': False, 'text': '<p>Or with the beloved <a href="https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/ObjectArrays.html#concat(T%5B%5D,%20T%5B%5D,%20java.lang.Class)" rel="noreferrer">Guava</a>:</p>\n\n<pre><code>String[] both = ObjectArrays.concat(first, second, String.class);\n</code></pre>\n\n<p>Also, there are versions for primitive arrays:</p>\n\n<ul>\n<li><code>Booleans.concat(first, second)</code></li>\n<li><code>Bytes.concat(first, second)</code></li>\n<li><code>Chars.concat(first, second)</code></li>\n<li><code>Doubles.concat(first, second)</code></li>\n<li><code>Shorts.concat(first, second)</code></li>\n<li><code>Ints.concat(first, second)</code></li>\n<li><code>Longs.concat(first, second)</code></li>\n<li><code>Floats.concat(first, second)</code></li>\n</ul>\n'}, {'answer_id': 5497557, 'author': 'Adham', 'author_id': 671613, 'author_profile': 'https://Stackoverflow.com/users/671613', 'pm_score': 0, 'selected': False, 'text': '<pre><code>Object[] obj = {"hi","there"};\nObject[] obj2 ={"im","fine","what abt u"};\nObject[] obj3 = new Object[obj.length+obj2.length];\n\nfor(int i =0;i&lt;obj3.length;i++)\n    obj3[i] = (i&lt;obj.length)?obj[i]:obj2[i-obj.length];\n</code></pre>\n'}, {'answer_id': 6295624, 'author': 'candrews', 'author_id': 791247, 'author_profile': 'https://Stackoverflow.com/users/791247', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s my slightly improved version of Joachim Sauer\'s concatAll. It can work on Java 5 or 6, using Java 6\'s System.arraycopy if it\'s available at runtime. This method (IMHO) is perfect for Android, as it work on Android &lt;9 (which doesn\'t have System.arraycopy) but will use the faster method if possible.</p>\n\n<pre><code>  public static &lt;T&gt; T[] concatAll(T[] first, T[]... rest) {\n    int totalLength = first.length;\n    for (T[] array : rest) {\n      totalLength += array.length;\n    }\n    T[] result;\n    try {\n      Method arraysCopyOf = Arrays.class.getMethod("copyOf", Object[].class, int.class);\n      result = (T[]) arraysCopyOf.invoke(null, first, totalLength);\n    } catch (Exception e){\n      //Java 6 / Android &gt;= 9 way didn\'t work, so use the "traditional" approach\n      result = (T[]) java.lang.reflect.Array.newInstance(first.getClass().getComponentType(), totalLength);\n      System.arraycopy(first, 0, result, 0, first.length);\n    }\n    int offset = first.length;\n    for (T[] array : rest) {\n      System.arraycopy(array, 0, result, offset, array.length);\n      offset += array.length;\n    }\n    return result;\n  }\n</code></pre>\n'}, {'answer_id': 6301908, 'author': 'Muhammad Haris Altaf', 'author_id': 789261, 'author_profile': 'https://Stackoverflow.com/users/789261', 'pm_score': 0, 'selected': False, 'text': '<p>The easiest way i could find is as following :</p>\n\n<pre>\n<code>\nList allFiltersList = Arrays.asList(regularFilters);\nallFiltersList.addAll(Arrays.asList(preFiltersArray));\nFilter[] mergedFilterArray = (Filter[]) allFiltersList.toArray();\n</code>\n</pre>\n'}, {'answer_id': 6318217, 'author': 'Oritm', 'author_id': 574736, 'author_profile': 'https://Stackoverflow.com/users/574736', 'pm_score': 3, 'selected': False, 'text': '<p>This is a converted function for a String array:</p>\n\n<pre><code>public String[] mergeArrays(String[] mainArray, String[] addArray) {\n    String[] finalArray = new String[mainArray.length + addArray.length];\n    System.arraycopy(mainArray, 0, finalArray, 0, mainArray.length);\n    System.arraycopy(addArray, 0, finalArray, mainArray.length, addArray.length);\n\n    return finalArray;\n}\n</code></pre>\n'}, {'answer_id': 6691787, 'author': 'Jeroen', 'author_id': 844342, 'author_profile': 'https://Stackoverflow.com/users/844342', 'pm_score': 2, 'selected': False, 'text': '<pre><code>Import java.util.*;\n\nString array1[] = {"bla","bla"};\nString array2[] = {"bla","bla"};\n\nArrayList&lt;String&gt; tempArray = new ArrayList&lt;String&gt;(Arrays.asList(array1));\ntempArray.addAll(Arrays.asList(array2));\nString array3[] = films.toArray(new String[1]); // size will be overwritten if needed\n</code></pre>\n\n<p>You could replace String by a Type/Class of your liking</p>\n\n<p>Im sure this can be made shorter and better, but it works and im to lazy to sort it out further...</p>\n'}, {'answer_id': 6777237, 'author': 'Sushim ', 'author_id': 856097, 'author_profile': 'https://Stackoverflow.com/users/856097', 'pm_score': 0, 'selected': False, 'text': '<p><strong>You can try this</strong></p>\n\n<pre><code> public static Object[] addTwoArray(Object[] objArr1, Object[] objArr2){\n    int arr1Length = objArr1!=null &amp;&amp; objArr1.length&gt;0?objArr1.length:0;\n    int arr2Length = objArr2!=null &amp;&amp; objArr2.length&gt;0?objArr2.length:0;\n    Object[] resutlentArray = new Object[arr1Length+arr2Length]; \n    for(int i=0,j=0;i&lt;resutlentArray.length;i++){\n        if(i+1&lt;=arr1Length){\n            resutlentArray[i]=objArr1[i];\n        }else{\n            resutlentArray[i]=objArr2[j];\n            j++;\n        }\n    }\n\n    return resutlentArray;\n}\n</code></pre>\n\n<p>U can type cast your array !!!</p>\n'}, {'answer_id': 7724875, 'author': 'francois', 'author_id': 989332, 'author_profile': 'https://Stackoverflow.com/users/989332', 'pm_score': 5, 'selected': False, 'text': '<p>A solution <strong>100% old java</strong> and <strong>without</strong> <code>System.arraycopy</code> (not available in GWT client for example):</p>\n\n<pre><code>static String[] concat(String[]... arrays) {\n    int length = 0;\n    for (String[] array : arrays) {\n        length += array.length;\n    }\n    String[] result = new String[length];\n    int pos = 0;\n    for (String[] array : arrays) {\n        for (String element : array) {\n            result[pos] = element;\n            pos++;\n        }\n    }\n    return result;\n}\n</code></pre>\n'}, {'answer_id': 7733971, 'author': 'Ephraim', 'author_id': 432499, 'author_profile': 'https://Stackoverflow.com/users/432499', 'pm_score': 3, 'selected': False, 'text': '<p>How about simply    </p>\n\n<pre><code>public static class Array {\n\n    public static &lt;T&gt; T[] concat(T[]... arrays) {\n        ArrayList&lt;T&gt; al = new ArrayList&lt;T&gt;();\n        for (T[] one : arrays)\n            Collections.addAll(al, one);\n        return (T[]) al.toArray(arrays[0].clone());\n    }\n}\n</code></pre>\n\n<p>And just do <code>Array.concat(arr1, arr2)</code>. As long as <code>arr1</code> and <code>arr2</code> are of the same type, this will give you another array of the same type containing both arrays. </p>\n'}, {'answer_id': 8728568, 'author': 'hpgisler', 'author_id': 757684, 'author_profile': 'https://Stackoverflow.com/users/757684', 'pm_score': 3, 'selected': False, 'text': '<p>Here a possible implementation in working code of the pseudo code solution written by silvertab. </p>\n\n<p>Thanks silvertab!</p>\n\n<pre class="lang-java prettyprint-override"><code>public class Array {\n\n   public static &lt;T&gt; T[] concat(T[] a, T[] b, ArrayBuilderI&lt;T&gt; builder) {\n      T[] c = builder.build(a.length + b.length);\n      System.arraycopy(a, 0, c, 0, a.length);\n      System.arraycopy(b, 0, c, a.length, b.length);\n      return c;\n   }\n}\n</code></pre>\n\n<p>Following next is the builder interface. </p>\n\n<p>Note: A builder is necessary because in java it is not possible to do </p>\n\n<p><code>new T[size]</code> </p>\n\n<p>due to generic type erasure:</p>\n\n<pre class="lang-java prettyprint-override"><code>public interface ArrayBuilderI&lt;T&gt; {\n\n   public T[] build(int size);\n}\n</code></pre>\n\n<p>Here a concrete builder implementing the interface, building a <code>Integer</code> array:</p>\n\n<pre class="lang-java prettyprint-override"><code>public class IntegerArrayBuilder implements ArrayBuilderI&lt;Integer&gt; {\n\n   @Override\n   public Integer[] build(int size) {\n      return new Integer[size];\n   }\n}\n</code></pre>\n\n<p>And finally the application / test:</p>\n\n<pre class="lang-java prettyprint-override"><code>@Test\npublic class ArrayTest {\n\n   public void array_concatenation() {\n      Integer a[] = new Integer[]{0,1};\n      Integer b[] = new Integer[]{2,3};\n      Integer c[] = Array.concat(a, b, new IntegerArrayBuilder());\n      assertEquals(4, c.length);\n      assertEquals(0, (int)c[0]);\n      assertEquals(1, (int)c[1]);\n      assertEquals(2, (int)c[2]);\n      assertEquals(3, (int)c[3]);\n   }\n}\n</code></pre>\n'}, {'answer_id': 9512746, 'author': 'Jerome', 'author_id': 811865, 'author_profile': 'https://Stackoverflow.com/users/811865', 'pm_score': -1, 'selected': False, 'text': '<p>In Haskell you can do something like that <code>[a, b, c] ++ [d, e]</code> to get <code>[a, b, c, d, e]</code>. These are Haskell lists concatenated but that\'d very nice to see a similar operator in Java for arrays. Don\'t you think so ? That\'s elegant, simple, generic and it\'s not that difficult to implement.</p>\n\n<p>If you want to, I suggest you to have a look at Alexander Hristov\'s work in his <a href="http://www.ahristov.com/tutoriales/java-compiler/duplicating-lexer.html" rel="nofollow">Hacking the OpenJDK compiler</a>. He explains how to modify javac source to create a new operator. His example consists in defining a \'**\' operator where <code>i ** j = Math.pow(i, j)</code>. One could take that example to implement an operator that concatenates two arrays of same type.<br></p>\n\n<p>Once you do that, you are bound to your customized javac to compile your code but the generated bytecode will be understood by any JVM. <br><br>Of course, you can implement your own array concatenatation method at your source level, there are many examples on how to do it in the other answers !<br>\n<br>\nThere are so many useful operators that could be added, this one would be one of them.</p>\n'}, {'answer_id': 10056834, 'author': 'filosofem', 'author_id': 1319411, 'author_profile': 'https://Stackoverflow.com/users/1319411', 'pm_score': -1, 'selected': False, 'text': '<p>Look at this elegant solution (if you need other type than char, change it):</p>\n\n<pre><code>private static void concatArrays(char[] destination, char[]... sources) {\n    int currPos = 0;\n    for (char[] source : sources) {\n        int length = source.length;\n        System.arraycopy(source, 0, destination, currPos, length);\n        currPos += length;\n    }\n}\n</code></pre>\n\n<p>You can concatenate a every count of arrays.</p>\n'}, {'answer_id': 10382513, 'author': 'user462990', 'author_id': 462990, 'author_profile': 'https://Stackoverflow.com/users/462990', 'pm_score': 2, 'selected': False, 'text': '<p>I found I had to deal with the case where the arrays can be null...</p>\n\n<pre><code>private double[] concat  (double[]a,double[]b){\n    if (a == null) return b;\n    if (b == null) return a;\n    double[] r = new double[a.length+b.length];\n    System.arraycopy(a, 0, r, 0, a.length);\n    System.arraycopy(b, 0, r, a.length, b.length);\n    return r;\n\n}\nprivate double[] copyRest (double[]a, int start){\n    if (a == null) return null;\n    if (start &gt; a.length)return null;\n    double[]r = new double[a.length-start];\n    System.arraycopy(a,start,r,0,a.length-start); \n    return r;\n}\n</code></pre>\n'}, {'answer_id': 11470232, 'author': 'Reto Höhener', 'author_id': 1124509, 'author_profile': 'https://Stackoverflow.com/users/1124509', 'pm_score': 4, 'selected': False, 'text': '<p>Please forgive me for adding yet another version to this already long list. I looked at every answer and decided that I really wanted a version with just one parameter in the signature. I also added some argument checking to benefit from early failure with sensible info in case of unexpected input.</p>\n\n<pre><code>@SuppressWarnings("unchecked")\npublic static &lt;T&gt; T[] concat(T[]... inputArrays) {\n  if(inputArrays.length &lt; 2) {\n    throw new IllegalArgumentException("inputArrays must contain at least 2 arrays");\n  }\n\n  for(int i = 0; i &lt; inputArrays.length; i++) {\n    if(inputArrays[i] == null) {\n      throw new IllegalArgumentException("inputArrays[" + i + "] is null");\n    }\n  }\n\n  int totalLength = 0;\n\n  for(T[] array : inputArrays) {\n    totalLength += array.length;\n  }\n\n  T[] result = (T[]) Array.newInstance(inputArrays[0].getClass().getComponentType(), totalLength);\n\n  int offset = 0;\n\n  for(T[] array : inputArrays) {\n    System.arraycopy(array, 0, result, offset, array.length);\n\n    offset += array.length;\n  }\n\n  return result;\n}\n</code></pre>\n'}, {'answer_id': 13112678, 'author': 'doles', 'author_id': 1118233, 'author_profile': 'https://Stackoverflow.com/users/1118233', 'pm_score': 3, 'selected': False, 'text': '<p>Wow! lot of complex answers here including some simple ones that depend on external dependencies. how about doing it like this:</p>\n\n<pre><code>String [] arg1 = new String{"a","b","c"};\nString [] arg2 = new String{"x","y","z"};\n\nArrayList&lt;String&gt; temp = new ArrayList&lt;String&gt;();\ntemp.addAll(Arrays.asList(arg1));\ntemp.addAll(Arrays.asList(arg2));\nString [] concatedArgs = temp.toArray(new String[arg1.length+arg2.length]);\n</code></pre>\n'}, {'answer_id': 15103456, 'author': 'Earth Engine', 'author_id': 812034, 'author_profile': 'https://Stackoverflow.com/users/812034', 'pm_score': 2, 'selected': False, 'text': "<p>Another way to think about the question. To concatenate two or more arrays, one have to do is to list all elements of each arrays, and then build a new array. This sounds like create a <code>List&lt;T&gt;</code> and then calls <code>toArray</code> on it. Some other answers uses <code>ArrayList</code>, and that's fine. But how about implement our own? It is not hard:</p>\n\n<pre><code>private static &lt;T&gt; T[] addAll(final T[] f, final T...o){\n    return new AbstractList&lt;T&gt;(){\n\n        @Override\n        public T get(int i) {\n            return i&gt;=f.length ? o[i - f.length] : f[i];\n        }\n\n        @Override\n        public int size() {\n            return f.length + o.length;\n        }\n\n    }.toArray(f);\n}\n</code></pre>\n\n<p>I believe the above is equivalent to solutions that uses <code>System.arraycopy</code>. However I think this one has its own beauty. </p>\n"}, {'answer_id': 17235840, 'author': 'Frimousse', 'author_id': 2509077, 'author_profile': 'https://Stackoverflow.com/users/2509077', 'pm_score': 2, 'selected': False, 'text': '<pre><code>String [] both = new ArrayList&lt;String&gt;(){{addAll(Arrays.asList(first)); addAll(Arrays.asList(second));}}.toArray(new String[0]);\n</code></pre>\n'}, {'answer_id': 18350255, 'author': 'h-rai', 'author_id': 1109689, 'author_profile': 'https://Stackoverflow.com/users/1109689', 'pm_score': 5, 'selected': False, 'text': '<pre><code>ArrayList&lt;String&gt; both = new ArrayList(Arrays.asList(first));\nboth.addAll(Arrays.asList(second));\n\nboth.toArray(new String[0]);\n</code></pre>\n'}, {'answer_id': 19666913, 'author': 'SuperCamp', 'author_id': 2782483, 'author_profile': 'https://Stackoverflow.com/users/2782483', 'pm_score': -1, 'selected': False, 'text': '<p>Should do the trick. This is assuming String[] first and String[] second</p>\n\n<pre><code>List&lt;String&gt; myList = new ArrayList&lt;String&gt;(Arrays.asList(first));\nmyList.addAll(new ArrayList&lt;String&gt;(Arrays.asList(second)));\nString[] both = myList.toArray(new String[myList.size()]);\n</code></pre>\n'}, {'answer_id': 20903551, 'author': 'Ricardo Vallejo', 'author_id': 3144146, 'author_profile': 'https://Stackoverflow.com/users/3144146', 'pm_score': 0, 'selected': False, 'text': '<p>This one works only with int but the idea is generic</p>\n\n<pre><code>public static int[] junta(int[] v, int[] w) {\n\nint[] junta = new int[v.length + w.length];\n\nfor (int i = 0; i &lt; v.length; i++) {            \n    junta[i] = v[i];\n}\n\nfor (int j = v.length; j &lt; junta.length; j++) {\n    junta[j] = w[j - v.length];\n}\n</code></pre>\n'}, {'answer_id': 23188881, 'author': 'Vitalii Fedorenko', 'author_id': 288671, 'author_profile': 'https://Stackoverflow.com/users/288671', 'pm_score': 9, 'selected': False, 'text': '<p>Using <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" rel="noreferrer"><code>Stream</code></a> in Java 8:</p>\n\n<pre><code>String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))\n                      .toArray(String[]::new);\n</code></pre>\n\n<p>Or like this, using <code>flatMap</code>:</p>\n\n<pre><code>String[] both = Stream.of(a, b).flatMap(Stream::of)\n                      .toArray(String[]::new);\n</code></pre>\n\n<p>To do this for a generic type you have to use reflection:</p>\n\n<pre><code>@SuppressWarnings("unchecked")\nT[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray(\n    size -&gt; (T[]) Array.newInstance(a.getClass().getComponentType(), size));\n</code></pre>\n'}, {'answer_id': 25026341, 'author': 'spacebiker', 'author_id': 1114732, 'author_profile': 'https://Stackoverflow.com/users/1114732', 'pm_score': 2, 'selected': False, 'text': '<p>I think the best solution with generics would be:</p>\n\n<pre><code>/* This for non primitive types */\npublic static &lt;T&gt; T[] concatenate (T[]... elements) {\n\n    T[] C = null;\n    for (T[] element: elements) {\n        if (element==null) continue;\n        if (C==null) C = (T[]) Array.newInstance(element.getClass().getComponentType(), element.length);\n        else C = resizeArray(C, C.length+element.length);\n\n        System.arraycopy(element, 0, C, C.length-element.length, element.length);\n    }\n\n    return C;\n}\n\n/**\n * as far as i know, primitive types do not accept generics \n * http://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types\n * for primitive types we could do something like this:\n * */\npublic static int[] concatenate (int[]... elements){\n    int[] C = null;\n    for (int[] element: elements) {\n        if (element==null) continue;\n        if (C==null) C = new int[element.length];\n        else C = resizeArray(C, C.length+element.length);\n\n        System.arraycopy(element, 0, C, C.length-element.length, element.length);\n    }\n    return C;\n}\n\nprivate static &lt;T&gt; T resizeArray (T array, int newSize) {\n    int oldSize =\n            java.lang.reflect.Array.getLength(array);\n    Class elementType =\n            array.getClass().getComponentType();\n    Object newArray =\n            java.lang.reflect.Array.newInstance(\n                    elementType, newSize);\n    int preserveLength = Math.min(oldSize, newSize);\n    if (preserveLength &gt; 0)\n        System.arraycopy(array, 0,\n                newArray, 0, preserveLength);\n    return (T) newArray;\n}\n</code></pre>\n'}, {'answer_id': 28466684, 'author': 'clément francomme', 'author_id': 4151755, 'author_profile': 'https://Stackoverflow.com/users/4151755', 'pm_score': 2, 'selected': False, 'text': '<p>How about :</p>\n\n<pre><code>public String[] combineArray (String[] ... strings) {\n    List&lt;String&gt; tmpList = new ArrayList&lt;String&gt;();\n    for (int i = 0; i &lt; strings.length; i++)\n        tmpList.addAll(Arrays.asList(strings[i]));\n    return tmpList.toArray(new String[tmpList.size()]);\n}\n</code></pre>\n'}, {'answer_id': 33018648, 'author': 'George', 'author_id': 791195, 'author_profile': 'https://Stackoverflow.com/users/791195', 'pm_score': 1, 'selected': False, 'text': '<pre><code>public int[] mergeArrays(int [] a, int [] b) {\n    int [] merged = new int[a.length + b.length];\n    int i = 0, k = 0, l = a.length;\n    int j = a.length &gt; b.length ? a.length : b.length;\n    while(i &lt; j) {\n        if(k &lt; a.length) {\n            merged[k] = a[k];\n            k++;\n        }\n        if((l - a.length) &lt; b.length) {\n            merged[l] = b[l - a.length];\n            l++;\n        }\n        i++;\n    }\n    return merged;\n}\n</code></pre>\n'}, {'answer_id': 33711992, 'author': 'Paul', 'author_id': 4908555, 'author_profile': 'https://Stackoverflow.com/users/4908555', 'pm_score': 4, 'selected': False, 'text': '<p>You could try converting it into a <code>ArrayList</code> and use the <code>addAll</code> method then convert back to an array.</p>\n<pre><code>List list = new ArrayList(Arrays.asList(first));\n  list.addAll(Arrays.asList(second));\n  String[] both = list.toArray();\n</code></pre>\n'}, {'answer_id': 35315750, 'author': 'Vaseph', 'author_id': 1912860, 'author_profile': 'https://Stackoverflow.com/users/1912860', 'pm_score': 4, 'selected': False, 'text': '<p>Another way with Java8 using Stream</p>\n\n<pre><code>  public String[] concatString(String[] a, String[] b){ \n    Stream&lt;String&gt; streamA = Arrays.stream(a);\n    Stream&lt;String&gt; streamB = Arrays.stream(b);\n    return Stream.concat(streamA, streamB).toArray(String[]::new); \n  }\n</code></pre>\n'}, {'answer_id': 35644035, 'author': 'Kamil Tomasz Jarmusik', 'author_id': 5642475, 'author_profile': 'https://Stackoverflow.com/users/5642475', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public static String[] toArray(String[]... object){\n    List&lt;String&gt; list=new ArrayList&lt;&gt;();\n    for (String[] i : object) {\n        list.addAll(Arrays.asList(i));\n    }\n    return list.toArray(new String[list.size()]);\n}\n</code></pre>\n'}, {'answer_id': 38448403, 'author': 'obwan02', 'author_id': 6554496, 'author_profile': 'https://Stackoverflow.com/users/6554496', 'pm_score': 0, 'selected': False, 'text': '<pre><code>Object[] mixArray(String[] a, String[] b)\nString[] s1 = a;\nString[] s2 = b;\nObject[] result;\nList&lt;String&gt; input = new ArrayList&lt;String&gt;();\nfor (int i = 0; i &lt; s1.length; i++)\n{\n    input.add(s1[i]);\n}\nfor (int i = 0; i &lt; s2.length; i++)\n{\n    input.add(s2[i]);\n}\nresult = input.toArray();\nreturn result;\n</code></pre>\n'}, {'answer_id': 39322165, 'author': 'Douglas Held', 'author_id': 399723, 'author_profile': 'https://Stackoverflow.com/users/399723', 'pm_score': 2, 'selected': False, 'text': '<p>Every single answer is copying data and creating a new array. This is not strictly necessary and is definitely NOT what you want to do if your arrays are reasonably large. Java creators already knew that array copies are wasteful and that is why they provided us System.arrayCopy() to do those outside Java when we have to.</p>\n\n<p>Instead of copying your data around, consider leaving it in place and draw from it where it lies. Copying data locations just because the programmer would like to organize them is not always sensible.</p>\n\n<pre><code>// I have arrayA and arrayB; would like to treat them as concatenated\n// but leave my damn bytes where they are!\nObject accessElement ( int index ) {\n     if ( index &lt; 0 ) throw new ArrayIndexOutOfBoundsException(...);\n     // is reading from the head part?\n     if ( index &lt; arrayA.length )\n          return arrayA[ index ];\n     // is reading from the tail part?\n     if ( index &lt; ( arrayA.length + arrayB.length ) )\n          return arrayB[ index - arrayA.length ];\n     throw new ArrayIndexOutOfBoundsException(...); // index too large\n}\n</code></pre>\n'}, {'answer_id': 40855217, 'author': 'user_3380739', 'author_id': 3380739, 'author_profile': 'https://Stackoverflow.com/users/3380739', 'pm_score': 2, 'selected': False, 'text': '<p>Here is the code by <a href="https://github.com/landawn/AbacusUtil" rel="nofollow noreferrer">AbacusUtil</a>.</p>\n\n<pre><code>String[] a = {"a", "b", "c"};\nString[] b = {"1", "2", "3"};\nString[] c = N.concat(a, b); // c = ["a", "b", "c", "1", "2", "3"]\n\n// N.concat(...) is null-safety.\na = null;\nc = N.concat(a, b); // c = ["1", "2", "3"]\n</code></pre>\n'}, {'answer_id': 40991067, 'author': 'Yashovardhan99', 'author_id': 7252861, 'author_profile': 'https://Stackoverflow.com/users/7252861', 'pm_score': -1, 'selected': False, 'text': '<pre><code>    void f(String[] first, String[] second) {\n    String[] both = new String[first.length+second.length];\n    for(int i=0;i&lt;first.length;i++)\n        both[i] = first[i];\n    for(int i=0;i&lt;second.length;i++)\n        both[first.length + i] = second[i];\n}\n</code></pre>\n\n<p>This one works without knowledge of any other classes/libraries etc.\nIt works for any data type. Just replace <code>String</code> with anything like <code>int</code>,<code>double</code> or <code>char</code>.\nIt works quite efficiently.</p>\n'}, {'answer_id': 42201601, 'author': 'Raj S. Rusia', 'author_id': 7178104, 'author_profile': 'https://Stackoverflow.com/users/7178104', 'pm_score': 4, 'selected': False, 'text': '<p>If you use this way so you no need to import any third party class.</p>\n\n<p>If you want concatenate <code>String</code></p>\n\n<p><strong>Sample code for concate two String Array</strong></p>\n\n<pre><code>public static String[] combineString(String[] first, String[] second){\n        int length = first.length + second.length;\n        String[] result = new String[length];\n        System.arraycopy(first, 0, result, 0, first.length);\n        System.arraycopy(second, 0, result, first.length, second.length);\n        return result;\n    }\n</code></pre>\n\n<p>If you want concatenate <code>Int</code></p>\n\n<p><strong>Sample code for concate two Integer Array</strong></p>\n\n<pre><code>public static int[] combineInt(int[] a, int[] b){\n        int length = a.length + b.length;\n        int[] result = new int[length];\n        System.arraycopy(a, 0, result, 0, a.length);\n        System.arraycopy(b, 0, result, a.length, b.length);\n        return result;\n    }\n</code></pre>\n\n<p><strong>Here is Main method</strong></p>\n\n<pre><code>    public static void main(String[] args) {\n\n            String [] first = {"a", "b", "c"};\n            String [] second = {"d", "e"};\n\n            String [] joined = combineString(first, second);\n            System.out.println("concatenated String array : " + Arrays.toString(joined));\n\n            int[] array1 = {101,102,103,104};\n            int[] array2 = {105,106,107,108};\n            int[] concatenateInt = combineInt(array1, array2);\n\n            System.out.println("concatenated Int array : " + Arrays.toString(concatenateInt));\n\n        }\n    }  \n</code></pre>\n\n<p>We can use this way also.</p>\n'}, {'answer_id': 46542530, 'author': 'c-chavez', 'author_id': 1042409, 'author_profile': 'https://Stackoverflow.com/users/1042409', 'pm_score': 0, 'selected': False, 'text': '<p>Yet another answer for algorithm lovers:</p>\n\n<pre><code>public static String[] mergeArrays(String[] array1, String[] array2) {\n    int totalSize = array1.length + array2.length; // Get total size\n    String[] merged = new String[totalSize]; // Create new array\n    // Loop over the total size\n    for (int i = 0; i &lt; totalSize; i++) {\n        if (i &lt; array1.length) // If the current position is less than the length of the first array, take value from first array\n            merged[i] = array1[i]; // Position in first array is the current position\n\n        else // If current position is equal or greater than the first array, take value from second array.\n            merged[i] = array2[i - array1.length]; // Position in second array is current position minus length of first array.\n    }\n\n    return merged;\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>String[] array1str = new String[]{"a", "b", "c", "d"}; \nString[] array2str = new String[]{"e", "f", "g", "h", "i"};\nString[] listTotalstr = mergeArrays(array1str, array2str);\nSystem.out.println(Arrays.toString(listTotalstr));\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>[a, b, c, d, e, f, g, h, i]\n</code></pre>\n'}, {'answer_id': 46972713, 'author': 'Hakim', 'author_id': 4800139, 'author_profile': 'https://Stackoverflow.com/users/4800139', 'pm_score': 0, 'selected': False, 'text': '<p>You can try this method which concatenates multiple arrays:</p>\n\n<pre><code>public static &lt;T&gt; T[] concatMultipleArrays(T[]... arrays)\n{\n   int length = 0;\n   for (T[] array : arrays)\n   {\n      length += array.length;\n   }\n   T[] result = (T[]) Array.newInstance(arrays.getClass().getComponentType(), length) ;\n\n   length = 0;\n   for (int i = 0; i &lt; arrays.length; i++)\n   {\n      System.arraycopy(arrays[i], 0, result, length, arrays[i].length);\n      length += arrays[i].length;\n   }\n\n   return result;\n}\n</code></pre>\n'}, {'answer_id': 49772469, 'author': 'rghome', 'author_id': 3800782, 'author_profile': 'https://Stackoverflow.com/users/3800782', 'pm_score': 7, 'selected': False, 'text': '<p>You can append the two arrays in two lines of code.</p>\n\n<pre><code>String[] both = Arrays.copyOf(first, first.length + second.length);\nSystem.arraycopy(second, 0, both, first.length, second.length);\n</code></pre>\n\n<p>This is a fast and efficient solution and will work for primitive types as well as the two methods involved are overloaded.</p>\n\n<p>You should avoid solutions involving ArrayLists, streams, etc as these will need to allocate temporary memory for no useful purpose.</p>\n\n<p>You should avoid <code>for</code> loops for large arrays as these are not efficient. The built in methods use block-copy functions that are extremely fast.</p>\n'}, {'answer_id': 49793485, 'author': 'Basil Battikhi', 'author_id': 2901129, 'author_profile': 'https://Stackoverflow.com/users/2901129', 'pm_score': 0, 'selected': False, 'text': '<p>In Java 8 </p>\n\n<pre><code>public String[] concat(String[] arr1, String[] arr2){\n    Stream&lt;String&gt; stream1 = Stream.of(arr1);\n    Stream&lt;String&gt; stream2 = Stream.of(arr2);\n    Stream&lt;String&gt; stream = Stream.concat(stream1, stream2);\n    return Arrays.toString(stream.toArray(String[]::new));\n}\n</code></pre>\n'}, {'answer_id': 52375659, 'author': 'BrownRecluse', 'author_id': 5143356, 'author_profile': 'https://Stackoverflow.com/users/5143356', 'pm_score': 1, 'selected': False, 'text': '<p>Non Java 8 solution:</p>\n\n<pre><code>public static int[] combineArrays(int[] a, int[] b) {\n        int[] c = new int[a.length + b.length];\n\n        for (int i = 0; i &lt; a.length; i++) {\n            c[i] = a[i];\n        }\n\n        for (int j = 0, k = a.length; j &lt; b.length; j++, k++) {\n            c[k] = b[j];\n        }\n\n        return c;\n    }\n</code></pre>\n'}, {'answer_id': 52950353, 'author': 'keisar', 'author_id': 1344070, 'author_profile': 'https://Stackoverflow.com/users/1344070', 'pm_score': 4, 'selected': False, 'text': '<p>Using Java 8+ streams you can write the following function:</p>\n\n<pre><code>private static String[] concatArrays(final String[]... arrays) {\n    return Arrays.stream(arrays)\n         .flatMap(Arrays::stream)\n         .toArray(String[]::new);\n}\n</code></pre>\n'}, {'answer_id': 53025243, 'author': 'avigaild', 'author_id': 10567980, 'author_profile': 'https://Stackoverflow.com/users/10567980', 'pm_score': 3, 'selected': False, 'text': '<p>This should be one-liner.</p>\n\n<pre><code>public String [] concatenate (final String array1[], final String array2[])\n{\n    return Stream.concat(Stream.of(array1), Stream.of(array2)).toArray(String[]::new);\n}\n</code></pre>\n'}, {'answer_id': 53181401, 'author': 'beaudet', 'author_id': 2730420, 'author_profile': 'https://Stackoverflow.com/users/2730420', 'pm_score': 3, 'selected': False, 'text': '<p>A generic static version that uses the high performing System.arraycopy without requiring a @SuppressWarnings annotation:</p>\n\n<pre><code>public static &lt;T&gt; T[] arrayConcat(T[] a, T[] b) {\n    T[] both = Arrays.copyOf(a, a.length + b.length);\n    System.arraycopy(b, 0, both, a.length, b.length);\n    return both;\n}\n</code></pre>\n'}, {'answer_id': 55320708, 'author': 'ZhekaKozlov', 'author_id': 706317, 'author_profile': 'https://Stackoverflow.com/users/706317', 'pm_score': 2, 'selected': False, 'text': '<p>This is probably the only generic and type-safe way:</p>\n\n<pre><code>public class ArrayConcatenator&lt;T&gt; {\n    private final IntFunction&lt;T[]&gt; generator;\n\n    private ArrayConcatenator(IntFunction&lt;T[]&gt; generator) {\n        this.generator = generator;\n    }\n\n    public static &lt;T&gt; ArrayConcatenator&lt;T&gt; concat(IntFunction&lt;T[]&gt; generator) {\n        return new ArrayConcatenator&lt;&gt;(generator);\n    }\n\n    public T[] apply(T[] array1, T[] array2) {\n        T[] array = generator.apply(array1.length + array2.length);\n        System.arraycopy(array1, 0, array, 0, array1.length);\n        System.arraycopy(array2, 0, array, array1.length, array2.length);\n        return array;\n    }\n}\n</code></pre>\n\n<p>And the usage is quite concise:</p>\n\n<pre><code>Integer[] array1 = { 1, 2, 3 };\nDouble[] array2 = { 4.0, 5.0, 6.0 };\nNumber[] array = concat(Number[]::new).apply(array1, array2);\n</code></pre>\n\n<p>(requires static import)</p>\n\n<p>Invalid array types are rejected:</p>\n\n<pre><code>concat(String[]::new).apply(array1, array2); // error\nconcat(Integer[]::new).apply(array1, array2); // error\n</code></pre>\n'}, {'answer_id': 58587509, 'author': 'Kaplan', 'author_id': 11199879, 'author_profile': 'https://Stackoverflow.com/users/11199879', 'pm_score': 0, 'selected': False, 'text': '<p><em>concatenates a series of arrays compact, fast and type-safe with lambda</em></p>\n\n<pre><code>@SafeVarargs\npublic static &lt;T&gt; T[] concat( T[]... arrays ) {\n  return( Stream.of( arrays ).reduce( ( arr1, arr2 ) -&gt; {\n      T[] rslt = Arrays.copyOf( arr1, arr1.length + arr2.length );\n      System.arraycopy( arr2, 0, rslt, arr1.length, arr2.length );\n      return( rslt );\n    } ).orElse( null ) );\n};\n</code></pre>\n\n<p>returns <code>null</code> when called without argument<br /></p>\n\n<p>eg. example with 3 arrays:</p>\n\n<pre><code>String[] a = new String[] { "a", "b", "c", "d" };\nString[] b = new String[] { "e", "f", "g", "h" };\nString[] c = new String[] { "i", "j", "k", "l" };\n\nconcat( a, b, c );  // [a, b, c, d, e, f, g, h, i, j, k, l]\n</code></pre>\n\n<p><br /><em>"…probably the only generic and type-safe way"</em> – adapted:</p>\n\n<pre><code>Number[] array1 = { 1, 2, 3 };\nNumber[] array2 = { 4.0, 5.0, 6.0 };\nNumber[] array = concat( array1, array2 );  // [1, 2, 3, 4.0, 5.0, 6.0]\n</code></pre>\n'}, {'answer_id': 60017520, 'author': 'JGFMK', 'author_id': 495157, 'author_profile': 'https://Stackoverflow.com/users/495157', 'pm_score': 0, 'selected': False, 'text': '<p>Just wanted to add, you can use <code>System.arraycopy</code> too:</p>\n\n<pre><code>import static java.lang.System.out;\nimport static java.lang.System.arraycopy;\nimport java.lang.reflect.Array;\nclass Playground {\n    @SuppressWarnings("unchecked")\n    public static &lt;T&gt;T[] combineArrays(T[] a1, T[] a2) {\n        T[] result = (T[]) Array.newInstance(a1.getClass().getComponentType(), a1.length+a2.length);\n        arraycopy(a1,0,result,0,a1.length);\n        arraycopy(a2,0,result,a1.length,a2.length);\n        return result;\n    }\n    public static void main(String[ ] args) {\n        String monthsString = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";\n        String[] months = monthsString.split("(?&lt;=\\\\G.{3})");\n        String daysString = "SUNMONTUEWEDTHUFRISAT";\n        String[] days = daysString.split("(?&lt;=\\\\G.{3})");\n        for (String m : months) {\n            out.println(m);\n        }\n        out.println("===");\n         for (String d : days) {\n            out.println(d);\n        }\n        out.println("===");\n        String[] results = combineArrays(months, days);\n        for (String r : results) {\n            out.println(r);\n        }\n        out.println("===");\n    }\n}\n</code></pre>\n'}, {'answer_id': 60188847, 'author': 'Areeha', 'author_id': 6834039, 'author_profile': 'https://Stackoverflow.com/users/6834039', 'pm_score': -1, 'selected': False, 'text': '<p>Here is what worked for me:</p>\n\n<pre><code>String[] data=null;\nString[] data2=null;\nArrayList&lt;String&gt; data1 = new ArrayList&lt;String&gt;();\nfor(int i=0; i&lt;2;i++) {\n   data2 = input.readLine().split(",");\n   data1.addAll(Arrays.asList(data2));\n   data= data1.toArray(new String[data1.size()]);\n   }\n</code></pre>\n'}, {'answer_id': 65484015, 'author': 'Oleksandr Tsurika', 'author_id': 1663094, 'author_profile': 'https://Stackoverflow.com/users/1663094', 'pm_score': 0, 'selected': False, 'text': '<p>I use next method to concatenate any number of arrays of the same type using java 8:</p>\n<pre><code>public static &lt;G&gt; G[] concatenate(IntFunction&lt;G[]&gt; generator, G[] ... arrays) {\n    int len = arrays.length;\n    if (len == 0) {\n        return generator.apply(0);\n    } else if (len == 1) {\n        return arrays[0];\n    }\n    int pos = 0;\n    Stream&lt;G&gt; result = Stream.concat(Arrays.stream(arrays[pos]), Arrays.stream(arrays[++pos]));\n    while (pos &lt; len - 1) {\n        result = Stream.concat(result, Arrays.stream(arrays[++pos]));\n    }\n    return result.toArray(generator);\n}\n</code></pre>\n<p>usage:</p>\n<pre><code> concatenate(String[]::new, new String[]{&quot;one&quot;}, new String[]{&quot;two&quot;}, new String[]{&quot;three&quot;}) \n</code></pre>\n<p>or</p>\n<pre><code> concatenate(Integer[]::new, new Integer[]{1}, new Integer[]{2}, new Integer[]{3})\n</code></pre>\n'}, {'answer_id': 65727399, 'author': 'rizesky', 'author_id': 6324746, 'author_profile': 'https://Stackoverflow.com/users/6324746', 'pm_score': 0, 'selected': False, 'text': '<p>I just discovered this question, sorry very late, and saw a lot of answers that were too far away,\nusing certain libraries, using the feature of converting data from an array to a stream and back to an array and so on. But,\nwe can just use a simple loop and the problem is done</p>\n<pre class="lang-java prettyprint-override"><code>public String[] concat(String[] firstArr,String[] secondArr){\n        //if both is empty just return\n        if(firstArr.length==0 &amp;&amp; secondArr.length==0)return new String[0];\n\n        String[] res = new String[firstArr.length+secondArr.length];\n        int idxFromFirst=0;\n\n        //loop over firstArr, idxFromFirst will be used as starting offset for secondArr\n        for(int i=0;i&lt;firstArr.length;i++){\n            res[i] = firstArr[i];\n            idxFromFirst++;\n        }\n\n        //loop over secondArr, with starting offset idxFromFirst (the offset track from first array)\n        for(int i=0;i&lt;secondArr.length;i++){\n            res[idxFromFirst+i]=secondArr[i];\n        }\n\n        return res;\n    }\n</code></pre>\n<p>Thats it all, right? he didnt say he care about the order or anything.\nThis should be the easiest way of it.</p>\n'}, {'answer_id': 67960387, 'author': 'Lakshitha Kanchana', 'author_id': 6696702, 'author_profile': 'https://Stackoverflow.com/users/6696702', 'pm_score': 0, 'selected': False, 'text': "<p>I have a simple method. You don't want to waste your time to research complex java functions or libraries. But the return type should be String.</p>\n<pre><code>String[] f(String[] first, String[] second) {\n\n    // Variable declaration part\n    int len1 = first.length;\n    int len2 = second.length;\n    int lenNew = len1 + len2;\n    String[] both = new String[len1+len2];\n\n    // For loop to fill the array &quot;both&quot;\n    for (int i=0 ; i&lt;lenNew ; i++){\n        if (i&lt;len1) {\n            both[i] = first[i];\n        } else {\n            both[i] = second[i-len1];\n        }\n    }\n\n    return both;\n\n}\n</code></pre>\n<p>So simple...</p>\n"}, {'answer_id': 69157437, 'author': 'Rajesh Patel', 'author_id': 7866838, 'author_profile': 'https://Stackoverflow.com/users/7866838', 'pm_score': 0, 'selected': False, 'text': "<p>Using Java Collections</p>\n<p>Well, Java doesn't provide a helper method to concatenate arrays. However, since Java 5, the Collections utility class has introduced an addAll(Collection&lt;? super T&gt; c, T… elements) method.</p>\n<p>We can create a List object, then call this method twice to add the two arrays to the list. Finally, we convert the resulting List back to an array:</p>\n<pre><code>static &lt;T&gt; T[] concatWithCollection(T[] array1, T[] array2) {\n    List&lt;T&gt; resultList = new ArrayList&lt;&gt;(array1.length + array2.length);\n    Collections.addAll(resultList, array1);\n    Collections.addAll(resultList, array2);\n\n    @SuppressWarnings(&quot;unchecked&quot;)\n    //the type cast is safe as the array1 has the type T[]\n    T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0);\n    return resultList.toArray(resultArray);\n}\n</code></pre>\n<p>Test</p>\n<pre><code>@Test\npublic void givenTwoStringArrays_whenConcatWithList_thenGetExpectedResult() {\n    String[] result = ArrayConcatUtil.concatWithCollection(strArray1, strArray2);\n    assertThat(result).isEqualTo(expectedStringArray);\n}\n\n</code></pre>\n"}, {'answer_id': 71449230, 'author': 'mkemper', 'author_id': 14763038, 'author_profile': 'https://Stackoverflow.com/users/14763038', 'pm_score': 0, 'selected': False, 'text': '<p>I see many generic answers with signatures such as public static  T[] concat(T[] a, T[] b) {} but these only work on Object arrays, not on primitive arrays, as far as I can work out. The code below works both on Object and primitive arrays, making it more generic...</p>\n<pre><code>public static &lt;T&gt; T concat(T a, T b) {\n        //Handles both arrays of Objects and primitives! E.g., int[] out = concat(new int[]{6,7,8}, new int[]{9,10});\n        //You get a compile error if argument(s) not same type as output. (int[] in example above)\n        //You get a runtime error if output type is not an array, i.e., when you do something like: int out = concat(6,7);\n        if (a == null &amp;&amp; b == null) return null;\n        if (a == null) return b;\n        if (b == null) return a;\n        final int aLen = Array.getLength(a);\n        final int bLen = Array.getLength(b);\n        if (aLen == 0) return b;\n        if (bLen == 0) return a;\n        //From here on we really need to concatenate!\n\n        Class componentType = a.getClass().getComponentType();\n        final T result = (T)Array.newInstance(componentType, aLen + bLen);\n        System.arraycopy(a, 0, result, 0, aLen);\n        System.arraycopy(b, 0, result, aLen, bLen);\n        return result;\n    }\n\n    public static void main(String[] args) {\n        String[] out1 = concat(new String[]{&quot;aap&quot;, &quot;monkey&quot;}, new String[]{&quot;rat&quot;});\n        int[] out2 = concat(new int[]{6,7,8}, new int[]{9,10});\n    }\n</code></pre>\n'}, {'answer_id': 72239759, 'author': 'J.R', 'author_id': 3156682, 'author_profile': 'https://Stackoverflow.com/users/3156682', 'pm_score': 1, 'selected': False, 'text': '<pre><code> /**\n     * With Java Streams\n     * @param first First Array\n     * @param second Second Array\n     * @return Merged Array\n     */\n    String[] mergeArrayOfStrings(String[] first, String[] second) {\n        return Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(String[]::new);\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/80476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2948/']