Join two arrays in Java?

I'd allocate an array with the total length of healthMessages1 and healthMessages2 and use System.arraycopy or two for loops to copy their contents. Here is a sample with System.arraycopy:

public class HelloWorld {

     public static void main(String []args) {

        int[] a = new int[] { 1, 2, 3};
        int[] b = new int[] { 3, 4, 5};
        int[] r = new int[a.length + b.length];
        System.arraycopy(a, 0, r, 0, a.length);
        System.arraycopy(b, 0, r, a.length, b.length);

        // prints 1, 2, 3, 4, 5 on sep. lines
        for(int x : r) {
            System.out.println(x);
        }            
     }         
}

This is more intuitive to write and you don't have to deal with array indexes:

Collection<HealthMessage> collection = new ArrayList<HealthMessage>();
collection.addAll(Arrays.asList(healthMessages1));
collection.addAll(Arrays.asList(healthMessages2));

HealthMessage[] healthMessagesAll = collection.toArray(new HealthMessage[] {});

.. but don't ask me about it's performance in contrast to System.arraycopy.


Using Apache Commons Collections API is a good way:

healthMessagesAll = ArrayUtils.addAll(healthMessages1,healthMessages2);

I would go with System.arraycopy

private static HealthMessage[] join(HealthMessage[] healthMessages1, HealthMessage[] healthMessages2)
{
    HealthMessage[] healthMessagesAll = new HealthMessage[healthMessages1.length + healthMessages2.length];

    System.arraycopy(healthMessages1, 0, healthMessagesAll, 0, healthMessages1.length);
    System.arraycopy(healthMessages2, 0, healthMessagesAll, healthMessages1.length, healthMessages2.length);

    return healthMessagesAll;
}

Tags:

Java