Array concatenation: Difference between revisions

Line 2,340:
 
=={{header|Java}}==
In Java, arrays are immutable, so you'll have to create a new array, and copy the contents of the two arrays into it.<br />
<syntaxhighlight lang="java5">public static Object[] concat(Object[] arr1, Object[] arr2) {
Luckily, Java offers the ''System.arraycopy'' method, which will save you the effort of creating the for-loops.<br />
Object[] res = new Object[arr1.length + arr2.length];
}</syntaxhighlight lang="java">
 
int[] concat(int[] arrayA, int[] arrayB) {
System.arraycopy(arr1, 0, res, 0, arr1.length);
System.arraycopy(arr2,int[] 0,array res,= arr1new int[arrayA.length, arr2+ arrayB.length)];
System.arraycopy(arr1arrayA, 0, resarray, 0, arr1arrayA.length);
 
System.arraycopy(arrayB, 0, array, arrayA.length, arrayB.length);
return resarray;
}</syntaxhighlight>
}
</syntaxhighlight>
If you wanted to use for-loops, possibly to mutate the data as it's concatenated, you can use the following.
<syntaxhighlight lang="java">
int[] concat(int[] arrayA, int[] arrayB) {
Objectint[] resarray = new Objectint[arr1arrayA.length + arr2arrayB.length];
for (int index = 0; index < arrayA.length; index++)
array[index] = arrayA[index];
for (int index = 0; index < arrayB.length; index++)
array[index + arrayA.length] = arrayB[index];
return array;
}
</syntaxhighlight>
A less idiomatic approach would be to use a ''List'', which is a mutable array, similar to a "vector" in other languages.<br />
I have used both arrays and ''List''s extensively and have not noticed any sort of performance degradation, they appear to work equally as fast.<br />
It's worth noting that the Java Collections Framework, which contains the ''List'' class, is built specifically for Objects and not necessarily primitive data-types. Despite this, it's still worth using for primitives, although the conversion to and from arrays is somewhat abstruse.
<syntaxhighlight lang="java">
int[] concat(int[] arrayA, int[] arrayB) {
List<Integer> list = new ArrayList<>();
for (int value : arrayA) list.add(value);
for (int value : arrayB) list.add(value);
int[] array = new int[list.size()];
for (int index = 0; index < list.size(); index++)
array[index] = list.get(index);
return array;
}
</syntaxhighlight>
 
=={{header|JavaScript}}==
118

edits