I would add the existing values to your new array as you traverse with the iterator, rather than initializing all the values in biggerArray
. There isn't an easy way to insert into the middle of an array like that (which is why you would normally use an ArrayList
for this sort of thing).
Something like:
itab = new ArrayIterator(s);
Student[] newArray = new Student[6];
int newIndex = 0;
Student nowy =new Student("Małgorzata", "Kopytko", 165642, 4);
for (itab.first(); !itab.isDone(); itab.next()) {
Student st = (Student) itab.current();
if (st.nrIndex > nowy.nrIndex) { //Not sure about the meaning of this condition, make sure you only add the new student once!
newArray[newIndex] = nowy;
newIndex++;
}
newArray[newIndex] = st;
newIndex++;
}
It's also interesting to take a look at how ArrayList
inplements this. It uses System.arraycopy
, with which you could take a similar approach to what you are doing, and have:
s = biggerArray(s);
itab = new ArrayIterator(s);
int index = 0;
Student nowy =new Student("Małgorzata", "Kopytko", 165642, 4);
for (itab.first(); !itab.isDone(); itab.next()) {
Student st = (Student) itab.current();
if (st.nrIndex >nowy.nrIndex) {
System.arraycopy(s, index, s, index + 1, 5 - index);
s[index] = nowy;
break;
}
index++;
}