J2ME的Vector另一种实现

一个简单又有效的Vector的实现类。

public final class LVector {
    public Object data[];
    public int count;
    public LVector(int i) {
        if (i <= 0) {
            i = 10;
        }
        data = new Object[i];
        count = 0;
    }

    public LVector(LVector tinyvector) {
        count = tinyvector.count;
        data = new Object[tinyvector.data.length];
        System.arraycopy(tinyvector.data, 0, data, 0, data.length);
    }

    public final int indexOf(Object obj, int start) {
        if (obj == null) {
            return -1;
        }
        for (int i = start; i < count; i++) {
            if (obj.equals(data[i])) {
                return i;
            }
        }

        return -1;
    }

    public final int lastIndexOf(Object obj, int start) {
        if (start >= count) {
            return -1;
        }
        for (int i = start; i >= 0; i--) {
            if (obj.equals(data[i])) {
                return i;
            }
        }

        return -1;
    }

    public final int removeElementAt(int i) {
        if (i >= count || i < 0) {
            return -1;
        }
        int j;
        if ((j = count - i - 1) > 0) {
            System.arraycopy(data, i + 1, data, i, j);
        }
        count--;
        data[count] = null;
        return 0;
    }

    public final int insertElementAt(Object obj, int i) {
        int pos = count + 1;
        if (i >= pos) {
            return -1;
        }
        if (pos > data.length) {
            grow(pos);
        }
        System.arraycopy(data, i, data, i + 1, count - i);
        data[i] = obj;
        count++;
        return 0;
    }

    public final void addElement(Object obj) {
        int i = count + 1;
        if (i > data.length) {
            grow(i);
        }
        data[count++] = obj;
    }

    private void grow(int i) {
        int len = data.length;
        Object src[] = data;
        int k = len * 2;
        if (k < i) {
            k = i;
        }
        data = new Object[k];
        System.arraycopy(src, 0, data, 0, count);
    }

}