2011-12-23 27 views
0

如何插入一系列要素的數組中的如何在數組中插入一系列元素?

當前的代碼以陣列插入一個元件如下:

public static void getArrayElement() 
{ 

    try 
    { 
     if(initialSize==1) 
     { 
      //Get the user input 
      System.out.print("Enter the element: "); 
      getElement = key.nextInt(); 

      //Assign the user input to the array 
      for(int i=0; i<index; i++) 
      { 
       array[i] = getElement; 
      } 

     } 

     //If the size of the array is not 1 use this 
     else 
     { 
      //Gets the user input 
      System.out.print("Enter the element: "); 
      getElement = key.nextInt(); 

      //Create a new empty array with a new size 
      int[] temp = new int[index]; 

      //Assign the old array into the new array 
      for(int j = 0; j < index-1; j++) 
      { 
       temp[j] = array[j]; 
      } 

      //Change the size of the old array 
      array = new int [index]; 

      //Assign the temporary array into the new array with its new size 
      for(int aSize = 0; aSize< array.length; aSize++) 
      { 
       array[aSize] = temp[aSize]; 
       int k = array.length; 
       array[k-1] = getElement; 
      } 

      //Pass the array into sortArray method for sorting 
      sortArray(array, index); 

     } 

      //Increment the index and initialSize 
      index++; 
      initialSize++; 
     } 
     catch(InputMismatchException e) 
    { 
      System.out.println("Invalid Input"); 
      System.exit(0); 
    } 

    } 

正如所看到的上面的代碼可在僅一個元件插入時間。但是,如果我想一次插入一堆元素,我該怎麼做?

+2

實現這一目標只是爲了記錄:'無效getArrayElement()'是非常誤導,因爲'的getXXX()'表示返回值。 – Thomas 2011-12-23 12:34:08

+0

其他問題:'鑰匙'是一個'掃描儀'嗎?爲什麼不使用列表而不是數組?這樣你就不必處理你自己的複製。 – Thomas 2011-12-23 12:36:35

+0

如果您需要維護排序的集合,爲什麼不使用PriorityQueue?如果你不需要,那麼ArrayList? – milan 2011-12-23 12:39:34

回答

1

如果keyScanner你可能只是這樣做:

while(key.hasNextInt()) { 
    int i = key.nextInt(); 
    //do with i whatever you want 
} 

我還建議使用一個列表,而不是一個數組。然後,只需將列表傳遞給Collections.sort(list)以保持排序。

雖然列表只允許您添加對象,但您可以使用自動裝箱功能,並在插入時將int轉換爲Integer

或者有支持原始列表的庫 - 例如Google Guava和Apache Commons應該提供一些庫。

另一種替代方案可能是像Apache Common的TreeBag這樣的排序集合,它允許您將多個重複項添加到排序結構中。

2

在找到答案之前,最好理解數組是什麼。

數組是一組存儲在連續內存 位置的齊次元素。

這使得該陣列需要知道大小的時候,他們被初始化爲從存儲器中保留足夠的空間的限制。這使得插入在父數組中完全不可能。爲此,您將不得不執行arraycopy或創建一個具有不同大小的新數組。

例如,

int[] array = new int[10]; //Initializes an integer array of size 10. 
for(int i=0;i<10;i++){ 
    array[i] = i; 
}//stores values from 0 to 9. 

現在,如果打算插入一個或「N」在開始元素,你必須要麼創建具有大小或「分組陣列+ 1的大小」一個新的數組「 prev數組的大小+ n「。並在開始時執行數組複製,然後插入。所以,如果你想要一個動態對象爲你做這件事(插入一個,批量插入),你將不得不定義數組可以容納的自定義容量。然後你將不得不根據自己的喜好來增加容量。

在這個問題上發展,你會重塑Java的ArrayList。所以最好在你的情況下使用它。

0

您想將temp的內容複製到數組中。您可以在一個最多兩個步驟

if (temp.length > array.length) array = new int[temp.length]; System.arraycopy(temp, 0, array, 0, temp.length) ;

+0

有關[javadoc]中的方法的更多信息(http://docs.oracle.com/javase/6/docs/api/java/朗/ System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29) – A4L 2011-12-23 13:30:30

相關問題