001/*
002 * Copyright (C) 2009-2011 Mathias Doenitz
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.parboiled.common;
018
019import java.lang.reflect.Array;
020
021public class ArrayBuilder<T> {
022
023    private T[] array;
024
025    public ArrayBuilder() {
026        array = null;
027    }
028
029    public ArrayBuilder(T... elements) {
030        array = elements;
031    }
032
033    public T[] get() {
034        return array;
035    }
036
037    @SuppressWarnings({"unchecked"})
038    public ArrayBuilder<T> add(T... elements) {
039        if (elements == null) return this;
040        if (array == null) {
041            array = elements;
042            return this;
043        }
044        T[] newArray = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + elements.length);
045        System.arraycopy(array, 0, newArray, 0, array.length);
046        System.arraycopy(elements, 0, newArray, array.length, elements.length);
047        array = newArray;
048        return this;
049    }
050
051    @SuppressWarnings({"unchecked"})
052    public ArrayBuilder<T> addNonNulls(T... elements) {
053        if (elements == null) return this;
054        if (array == null) {
055            array = elements;
056            return this;
057        }
058        int nonNulls = 0;
059        for (T element : elements) {
060            if (element != null) nonNulls++;
061        }
062        if (nonNulls == 0) return this;
063
064        T[] newArray = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + nonNulls);
065        System.arraycopy(array, 0, newArray, 0, array.length);
066        for (int i = 0, j = array.length; i < elements.length; i++) {
067            T element = elements[i];
068            if (element != null) {
069                newArray[j++] = element;
070            }
071        }
072        array = newArray;
073        return this;
074    }
075
076}