如何插入一系列要素的數組中的如何在數組中插入一系列元素?
當前的代碼以陣列插入一個元件如下:
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);
}
}
正如所看到的上面的代碼可在僅一個元件插入時間。但是,如果我想一次插入一堆元素,我該怎麼做?
實現這一目標只是爲了記錄:'無效getArrayElement()'是非常誤導,因爲'的getXXX()'表示返回值。 – Thomas 2011-12-23 12:34:08
其他問題:'鑰匙'是一個'掃描儀'嗎?爲什麼不使用列表而不是數組?這樣你就不必處理你自己的複製。 – Thomas 2011-12-23 12:36:35
如果您需要維護排序的集合,爲什麼不使用PriorityQueue?如果你不需要,那麼ArrayList? – milan 2011-12-23 12:39:34