Question

I'm playing with array and iterator. I don't want to use collections. Just simple iterator and methods defined by myself. I have set of students in array (size of array is equal to the number of students) and they are in chronogical order (by student index (ID) number - 123456, 162475 in constructor etc.). So I want to create new array which is bigger than previous one (by one element) and add new student, but with saving the chronogical order. I have method that create bigger array and overwrite the reference to the old one, but I don't know how to add element in specific place using iterator. Using for() with it's array[i+1]=array[i] would be easy, but I don't know how to do it with iterator.

that's a part of my code:

public class GrupaStud {

public static void main(String[] args) {
    Student [] s = new Student[5];
    s[0]=new Student("Katarzyna", "Gryzipiórko", 123456, 5);
    s[1]=new Student("Bartosz", "Polański", 162475, 4);
    s[2]=new Student("Heniek", "Zając", 175642, 3);
    s[3]=new Student("Konstanty", "Mołotow", 432156, 2);
    s[4]=new Student("Bogdan", "Cichowlaz", 666555, 2.5);


    ArrayIterator itab = new  ArrayIterator(s);


    s = biggerArray(s);
       itab = new ArrayIterator(s);
       Student nowy =new Student("Małgorzata", "Kopytko", 165642, 4);
       for (itab.first(); !itab.isDone(); itab.next()) {
             Student st = (Student) itab.current();
    //in my mind that if need to check if index number of current element is bigger than  
     //int index above (165642) , but exactly here I don't know, how to add Student nowy 
    //to the array with moving rest of elements 
             if (st.nrIndex >nowy.nrIndex)     

    }
}

public static Student[] biggerArray(Student[] s)
{
        Student[] newArray = new Student[6];
        for (int i=0; i<s.length; i++)
            newArray[i] = s[i];
        return newArray;
}

}
Was it helpful?

Solution

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++;
}

OTHER TIPS

You should consider using an ArrayList instead which handles insertion better. Otherwise, you will need to shift all of the elements over in the array. ArrayList also automatically expand for you, so they are good when size is uncertain.

ArrayList<Student> students = new ArrayList<Student>();
students.add(student1);
students.add(student2);
students.add(student3);

int insertionIndex = 1;
students.add(insertionIndex, student4);

This does as specified. It accepts the original array and a to-insert-into array, which must be exactly one greater in length (well, at least one greater). Since it is generified to work with all (non-primitive) types, it cannot create the array itself.

The function:

public static final <O> O[] getNewArrayWithInserted(int insertIdx, O toInsert, O[] orig_arr, O[] arr_toInsInto)  {
   int idx = -1;
   try  {
      for(O o : orig_arr)  {
         idx++;                    //First iteration: was -1, now 0
         if(idx < insertIdx)  {
            arr_toInsInto[idx] = o;
            continue;
         }
         if(idx == insertIdx)  {
            arr_toInsInto[idx++] = toInsert;
         }
         arr_toInsInto[idx] = o;
      }
   }  catch(ArrayIndexOutOfBoundsException abx)  {
      throw  new ArrayIndexOutOfBoundsException("idx=" + idx + ", insertIdx=" + insertIdx + ", orig_arr.length=" + orig_arr.length + ", arr_toInsInto.length=" + arr_toInsInto.length + ", original error:" + abx);
   }
   return  arr_toInsInto;
}

Which is called with (index to insert-at, followed by the value to insert):

Integer[] intArr2 = ManualArrayInsertWItrIntoNewArray.<Integer>getNewArrayWithInserted(3, 4, intArr, new Integer[intArr.length + 1]);

Full example:

   import  java.util.Arrays;
/**
   <P>{@code java ManualArrayInsertWItrIntoNewArray}</P>
 **/
public class ManualArrayInsertWItrIntoNewArray  {
   public static final void main(String[] ignored)  {

      //You don't have to prefix it with ManualArrayInsertWItr in this static main,
      //but it's normally called this way.
      Integer[] intArr = new Integer[] {1, 2, 3, 5, 6, 7, 8, 9};

      Integer[] intArr2 = ManualArrayInsertWItrntoNewArray.<Integer>getNewArrayWithInserted(3, 4,
         intArr, new Integer[intArr.length + 1]);

      System.out.println("Original: " + Arrays.toString(intArr));
      System.out.println("New with insert: " + Arrays.toString(intArr2));
   }
   public static final <O> O[] getNewArrayWithInserted(int insertIdx, O toInsert, O[] orig_arr, O[] arr_toInsInto)  {

      int idx = -1;

      try  {
         for(O o : orig_arr)  {
            idx++;                    //First iteration: was -1, now 0
            if(idx < insertIdx)  {
               arr_toInsInto[idx] = o;
               continue;
            }

            if(idx == insertIdx)  {
               arr_toInsInto[idx++] = toInsert;
            }
            arr_toInsInto[idx] = o;
         }
      }  catch(ArrayIndexOutOfBoundsException abx)  {
         throw  new ArrayIndexOutOfBoundsException("idx=" + idx + ", insertIdx=" + insertIdx + ", orig_arr.length=" + orig_arr.length + ", arr_toInsInto.length=" + arr_toInsInto.length + ", original error:" + abx);
      }
      return  arr_toInsInto;
   }
}

Output:

[C:\java_code\]java ManualArrayInsertWItrIntoNewArray
Original: [1, 2, 3, 5, 6, 7, 8, 9]
New with insert: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top