How to Concatenate Two Arrays in Java

How to concat two string arrays in Java

It's not enough to import a type. You need to actually provide that type on the classpath when compiling your code.

It seems

can not resolve "import org.apache.commons.lang3.ArrayUtil"

like you haven't provided the jar containing the type above on your classpath.

Combine two integer arrays

You can't add them directly, you have to make a new array and then copy each of the arrays into the new one. System.arraycopy is a method you can use to perform this copy.

int[] array1and2 = new int[array1.length + array2.length];
System.arraycopy(array1, 0, array1and2, 0, array1.length);
System.arraycopy(array2, 0, array1and2, array1.length, array2.length);

This will work regardless of the size of array1 and array2.

How to merge two integer arrays in ascending order?

Assuming that you are looking to merge two sorted arrays, you could do it like this.

public static int[] merge(int array1[], int array2[]) {
int i = 0, j = 0, k = 0;
int size1 = array1.length;
int size2 = array2.length;
int[] result = new int[size1 + size2];

while (i < size1 && j < size2) {
if (array1[i] < array2[j]) {
result[k++] = array1[i++];
} else {
result[k++] = array2[j++];
}
}

// Store remaining elements
while (i < size1) {
result[k++] = array1[i++];
}

while (j < size2) {
result[k++] = array2[j++];
}

return result;

}

Join two arrays in Java?

Using Apache Commons Collections API is a good way:

healthMessagesAll = ArrayUtils.addAll(healthMessages1,healthMessages2);

How do I concatenate a certain amount of arrays?

Yes, problem is in destPos param, try so:

private static String[] concat(List<String[]> arrays) {
int length = 0;

for (String[] array : arrays)
length += array.length;

String[] first = arrays.get(0);
String[] result = Arrays.copyOf(first, length);

int index = first.length;

for (int i = 1; i < arrays.size(); i++) {
String[] array = arrays.get(i);
System.arraycopy(array, 0, result, index, array.length);
index += array.length;
}

return result;
}


Related Topics



Leave a reply



Submit