Concatenate two arrays in Java

This example shows how to concatenate two arrays. This can be achieved in more than one way but this example is quite easy and straight forward.
The List interface of the Collections framework contains a method called toArray() which converts the list into a regular array of specified type. We will use this to get the final concatenated array, but first we add elements of both arrays to the list by calling addAll(). This method takes a Collection as parameter, so we must convert both arrays to a collection. In the example below we have used the asList() method of the Arrays class to do this.

So basically what the code does is to convert the initial arrays to lists and add the elements of each to this one list, then that list is converted back to only one array. Finally the elements of the new array is printed out:

The output from the code above is:

The number of arrays to concatenate is not limited to two, but can be any number of arrays.

Search for more Java info on this site here:
Custom Search

Please type any questions here.