package fanch.multijeu.common.core;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Arrays;

public class ObjectVector<T> implements Serializable {

    protected Class<T> mClass;
    protected T[] mData;
    protected int mSize=16;
    protected int mAllocate=16;

    public ObjectVector(Class<T> c, int size)
    {
        mClass=c;
        mSize=size;
        mData = (T[])Array.newInstance(mClass, size);
        mAllocate=size;
    }

    public void resize(int n)
    {
        int size=mAllocate;
        while (size<n)
            size=size*2;
        mAllocate=size;
        T[] old = mData;
        mData= (T[])Array.newInstance(mClass, n);
        mAllocate=n;
        System.arraycopy(old, 0, mData, 0, mSize);
    }

    public void add(T[] t)
    {
        int tl = t.length;
        int n = tl+mSize;
        if(n>mAllocate)
            resize(n);
        System.arraycopy(t, 0, mData, mSize, tl);
        mSize+=tl;
    }

    public void add(T[] t, int offset, int len)
    {
        int tl = len;
        int n = tl+mSize;
        if(n>mAllocate)
            resize(n);
        System.arraycopy(t, offset, mData, mSize, tl);
        mSize+=tl;
    }

    public void add(T t)
    {
        if(mSize+1>mAllocate)
            resize(mSize+1);
        mData[mSize]=t;
        mSize++;
    }

    public T[] toArray()
    {
        return Arrays.copyOfRange(mData, 0, mSize-1);
    }


}
