【问题标题】:How to add element to the middle of the array using Iterator in Java?如何使用 Java 中的迭代器将元素添加到数组的中间?
【发布时间】:2014-03-03 18:02:53
【问题描述】:

我在玩数组和迭代器。我不想使用集合。只是我自己定义的简单迭代器和方法。 我在数组中有一组学生(数组的大小等于学生的数量),它们按时间顺序排列(按学生索引(ID)编号 - 构造函数中的 123456、162475 等)。所以我想创建一个比前一个(一个元素)大的新数组并添加新学生,但要保存时间顺序。我有创建更大数组并覆盖对旧数组的引用的方法,但我不知道如何使用迭代器在特定位置添加元素。使用 for() 和它的 array[i+1]=array[i] 会很容易,但我不知道如何使用迭代器。

这是我的代码的一部分:

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

}

【问题讨论】:

    标签: java arrays iterator add


    【解决方案1】:

    当您使用迭代器遍历时,我会将现有值添加到新数组中,而不是初始化biggerArray 中的所有值。没有一种简单的方法可以插入到这样的数组中间(这就是为什么您通常会使用 ArrayList 来处理这类事情)。

    类似:

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

    看看ArrayList 如何实现这一点也很有趣。它使用System.arraycopy,您可以使用它对您正在做的事情采取类似的方法,并且:

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

    【讨论】:

    • hmmm...你第二个命题中的“大小”是什么意思?
    • 是的,忘了这是硬编码的。应该是 5,size-index 正在尝试获取需要复制的项目数,因为它们在我们插入的项目之后
    • yup :) 你的代码还有一个错误,但我按照文档修复了它。它应该是 System.arraycopy(...),但我的代码正在运行,并且该人被正确添加:) 谢谢 :) 现在我需要仔细考虑,它究竟是如何工作的,因为它很聪明 :)
    【解决方案2】:

    您应该考虑改用 ArrayList 来更好地处理插入。否则,您将需要在数组中移动所有元素。 ArrayList 也会自动为你扩展,所以在大小不确定的情况下它们是很好的。

    ArrayList<Student> students = new ArrayList<Student>();
    students.add(student1);
    students.add(student2);
    students.add(student3);
    
    int insertionIndex = 1;
    students.add(insertionIndex, student4);
    

    【讨论】:

    • 是的,我知道所有这些,并且我知道在这种情况下如何使用 ArrayList,但是我需要在简单的数组中实现那个 add 方法,并移动其余元素并使用迭代器。而且我不知道该怎么做:) for(int i=0; i
    • @RIPI 抱歉,我刚刚读到您不想使用集合。
    【解决方案3】:

    这是按照指定的方式进行的。它接受原始数组和一个 to-insert-into 数组,该数组的长度必须恰好大一(嗯,至少大一)。由于它被泛化为适用于所有(非原始)类型,因此它不能自己创建数组。

    功能:

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

    使用(insert-at 的索引,后跟要插入的值)调用:

    Integer[] intArr2 = ManualArrayInsertWItrIntoNewArray.&lt;Integer&gt;getNewArrayWithInserted(3, 4, intArr, new Integer[intArr.length + 1]);

    完整示例:

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

    输出:

    [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]
    

    【讨论】:

      猜你喜欢
      • 2015-02-07
      • 2016-11-30
      • 2023-04-02
      • 2012-07-22
      • 2011-12-23
      • 2018-03-12
      • 1970-01-01
      • 2015-05-14
      • 2012-05-08
      相关资源
      最近更新 更多