Dynamic Array of ints in j2me

倖福魔咒の 提交于 2019-12-22 15:35:09

问题


I want to do a simple dynamic array of ints in my j2me application,

The only dynamic array I see is "java.util.Vector" and this one doesn't seem to accept an int as a new element (only wants Objects).

So how do I go around fixing that problem?


回答1:


public class DynamicIntArray
{
    private static final int CAPACITY_INCREMENT = 10;
    private static final int INITIAL_CAPACITY   = 10;

    private final int capacityIncrement;

    public int   length = 0;
    public int[] array;

    public DynamicIntArray(int initialCapacity, int capacityIncrement)
    {
        this.capacityIncrement = capacityIncrement;
        this.array = new int[initialCapacity];
    }

    public DynamicIntArray()
    {
        this(CAPACITY_INCREMENT, INITIAL_CAPACITY);
    }

    public int append(int i)
    {
        final int offset = length;
        if (offset == array.length)
        {
            int[] old = array;
            array = new int[offset + capacityIncrement];
            System.arraycopy(old, 0, array, 0, offset);
        }
        array[length++] = i;
        return offset;
    }


    public void removeElementAt(int offset)
    {
        if (offset >= length)
        {
            throw new ArrayIndexOutOfBoundsException("offset too big");
        }

        if (offset < length)
        {
            System.arraycopy(array, offset+1, array, offset, length-offset-1);
            length--;
        }
    }
}

Doesn't have a setAt() method, but I'm sure you get the idea.




回答2:


You need to box the int in an Integer.

v.addElement(new Integer(1));


来源:https://stackoverflow.com/questions/1322683/dynamic-array-of-ints-in-j2me

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!