понеділок, 28 лютого 2011 р.

Quick merge of two arrays in Java

Given two arrays, the goal is to get a concatenation of two. You may go through lands of JCF if you want, but also you may be puzzled if this can be done without it. I did.

Here is the code:

public class Utils {
    public static <T> T[] mergeArrays(T[] a, T[] b) {

        if (a == null || a.length == 0) return b;
        if (b == null || b.length == 0) return a;

        T[] m = (T[]) Array.newInstance(a.getClass().getComponentType(), a.length + b.length);

        System.arraycopy(a, 0, m, 0, a.length);
        System.arraycopy(b, 0, m, a.length, b.length);

        return m;

The first key point here, that we create new array instance with the help of Reflection API, using Array.newInstance() method.

The second key point is we obtain array element type at runtime with Class.getComponentType() method.

And final point is we use System.arraycopy() method to copy array contents, which is native call and is fastest you can get on JVM.

This doesn't work on arrays of primitive types, but version for primitives is as easy as search and replace T with required primitive type.

Немає коментарів:

Дописати коментар