concatenate two array together - Android java.lang

Android examples for java.lang:array union merge

Description

concatenate two array together

Demo Code


//package com.java2s;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;

import java.util.List;

public class Main {
    /**//  w w w  . j  a v a  2 s  .  co  m
     * @return a new list containing all values in both lists
     */
    public static <T> T[] concatenate(T[] listA, T[] listB) {
        if (isEmpty(listA)) {
            return listB;
        }

        if (isEmpty(listB)) {
            return listA;
        }

        int listALength = listA.length;
        int listBLength = listB.length;

        @SuppressWarnings("unchecked")
        T[] listC = (T[]) Array.newInstance(listA.getClass()
                .getComponentType(), listALength + listBLength);
        System.arraycopy(listA, 0, listC, 0, listALength);
        System.arraycopy(listB, 0, listC, listALength, listBLength);

        return listC;
    }

    /**
     * @return a new list containing all values in both lists
     */
    public static <T> List<T> concatenate(List<T> listA, List<T> listB) {
        if (isEmpty(listA)) {
            return listB;
        }

        if (isEmpty(listB)) {
            return listA;
        }

        List<T> listC = cloneList(listA);
        listC.addAll(listB);

        return listC;
    }

    /**
     * Is this list empty. Checks for null as well as size.
     *
     * @return true if empty, false if not
     */
    public static boolean isEmpty(Collection collection) {
        return collection == null || collection.isEmpty();
    }

    /**
     * Is this list empty. Checks for null as well as size.
     *
     * @return true if empty, false if not
     */
    public static boolean isEmpty(Object[] collection) {
        return collection == null || collection.length == 0;
    }

    /**
     * Clone the passed list
     *
     * @return the cloned list
     */
    public static <T extends Object> List<T> cloneList(List<T> list) {
        List<T> clone = new ArrayList<>(list.size());
        for (T item : list) {
            clone.add(item);
        }
        return clone;
    }
}

Related Tutorials