Inserting a element in the middle of the array
Hey!
I´m writing a template with a array as a structure,working on a function atm,that should insert a element in the array by me specifing the position(index) of it.
The trouble i´m having is,that when i try to insert a element in a position that allrdy has a element in it(as it should,since i dont want any "holes" in the array),i cant see to get the "pushing" of elements done properly.
for example if the array with the capacity of 3,contain elements {0,2},and insert a integer 1 at position
[1],i want the content of the array become {0,1,2}
I got the extension of the array working,so it should "extend" the array if the is not enough space.
But i´m really stack on the pushing of the elements part,any help would be appreciated!
the code i wrote so far is:
Code:
public void add(T elem, int pos)
{
if(pos>this.capacity)
{
System.out.println("Invalid Position!");
}
if(this.nrofelements==this.capacity)
{
T[] tmp;
tmp=(T[])new Object[capacity];
for(int i=0;i<capacity;i++)
{
tmp[i]=this.elements[i];
}
this.capacity+=3;
this.elements=(T[])new Object[capacity];
}
if(this.elements[pos]==null)
{
this.elements[pos]=elem;
nrofelements++;
}
else
{
this.capacity+=1;
T[] tmp;
tmp=(T[])new Object[capacity];
tmp=this.elements;
this.elements=(T[])new Object[capacity];
for(int i=0;i<pos;i++)
{
this.elements[i]=tmp[i];
}
for(int i=pos+1;i<this.capacity;i++)
{
this.elements[i+1]=tmp[i];
}
this.elements[pos]=elem;
nrofelements++;
}
}
this is probably more simple than i´m making it to be,hope some1 can help me out,thanks in advance!