ArrayExpander.java Source code

Java tutorial

Introduction

Here is the source code for ArrayExpander.java

Source

//package com.witframework.util;

import java.lang.reflect.Array;

public final class ArrayExpander {
    public static Object merge(Object array1, Object array2) {
        if (array1 == null) {
            return null;
        }
        if (array2 == null) {
            return array1;
        }
        Class c = array1.getClass();
        if (c.isArray() && array2.getClass().isArray()) {
            Class cc = c.getComponentType();
            Object newArray = Array.newInstance(cc, Array.getLength(array1) + Array.getLength(array2));
            System.arraycopy(array1, 0, newArray, 0, Array.getLength(array1));
            System.arraycopy(array2, 0, newArray, Array.getLength(array1), Array.getLength(array2));
            return newArray;
        } else {
            throw new ClassCastException("need  array");
        }

    }

    public static Object expand(Object array, int newSize) {
        if (array == null) {
            return null;
        }
        Class c = array.getClass();
        if (c.isArray()) {
            int len = Array.getLength(array);
            if (len >= newSize) {
                return array;
            } else {
                Class cc = c.getComponentType();
                Object newArray = Array.newInstance(cc, newSize);
                System.arraycopy(array, 0, newArray, 0, len);
                return newArray;
            }
        } else {
            throw new ClassCastException("need  array");
        }
    }

    public static Object expandAtHead(Object array, int newSize) {
        if (array == null) {
            return null;
        }
        Class c = array.getClass();
        if (c.isArray()) {
            int len = Array.getLength(array);
            if (len >= newSize) {
                return array;
            } else {
                Class cc = c.getComponentType();
                Object newArray = Array.newInstance(cc, newSize);
                System.arraycopy(array, 0, newArray, newSize - len, len);
                return newArray;
            }
        } else {
            throw new ClassCastException("need  array");
        }
    }
}