2

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?

kostia
  • 6,161
  • 3
  • 19
  • 23

2 Answers2

6

You need to box the int in an Integer.

v.addElement(new Integer(1));
Thomas Lundström
  • 1,589
  • 1
  • 13
  • 18
  • I ended up using that, the problem is, the best way I found to extract the value is "((Integer)(v.elementAt(index))).intValue()". Is it a java thing or what? – kostia Aug 25 '09 at 17:30
  • Use Generics. Vector v = Vector(); Integer i = v.elementAt(index); – Vijay Dev Aug 26 '09 at 10:07
  • You can use generics to type your Vector and then you don't return Objects with elementAt but Inegers instead. Try: Vector v = new Vector(); v.elementAt(index) Autoboxing will convert the Integer to an int for you, no need to use intValue. – Steve Claridge Aug 26 '09 at 10:07
  • 2
    Ain't no generics or autoboxing in J2ME, unfortunately. – izb Aug 26 '09 at 10:24
  • 1
    consider changing the answer to this one. – LolaRun Mar 23 '11 at 15:32
5
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.

izb
  • 50,101
  • 39
  • 117
  • 168
  • 1
    I guess DEFAULT_CAPACITY_INCREMENT, DEFAULT_INITIAL_CAPACITY should not have DEFAULT_ prefix? – Lukasz Apr 27 '11 at 13:09