Return to Snippet

Revision: 13946
at May 14, 2009 04:59 by kungfoo


Initial Code
package ch.hsr.ifs.liquid.util;

import static java.lang.System.arraycopy;

import java.lang.reflect.Array;

public class Arrays {
	private static final int ENLARGE_FACTOR = 2;

	public static <T> T[] enlargeArray(T[] array) {
		T[] enlargedArray = initArray(array, array.length * ENLARGE_FACTOR);
		arraycopy(array, 0, enlargedArray, 0, array.length);
		return enlargedArray;
	}
	
	public static <T> T[] trimArray(T[] array, int length) {
		T[] trimmedArray = initArray(array, length);
		arraycopy(array, 0, trimmedArray, 0, length);
		return trimmedArray;
	}

	public static <T> T[] composeArray(T[] array1, T[] array2) {
		int length1 = array1.length;
		int length2 = array2.length;

		T[] composedArray = initArray(array1, length1 + length2);

		arraycopy(array1, 0, composedArray, 0, length1);
		arraycopy(array2, 0, composedArray, length1, length2);

		return composedArray;
	}
	
	@SuppressWarnings("unchecked")
	private static <T> T[] initArray(T[] array, int newSize) {
		return (T[]) Array.newInstance(array.getClass().getComponentType(), newSize);
	}
}

Initial URL

                                

Initial Description

                                

Initial Title
Resizing Generic Arrays in Java in A Generic Way

Initial Tags
java

Initial Language
Java