2

この機能は、選択したインデックスに要素を追加し、配列要素内の他のすべてを押し下げることになっています。たとえば、次の配列があるとします。

[0] = zero
[1] = one
[2] = two

インデックス 0 に NEWZERO という別の要素を追加すると、配列は次のようになります。

[0] = NEWZERO
[1] = zero 
[2] = one 
[3] = two

しかし、現在 IndexOutOfBounds 例外が発生しており、機能しません。

PS 組み込みの ArrayList ライブラリは使用したくありません。自動的に実行されます。

    public void insert(int i, String s) {

    if (array[i] == null) {
        array[i] = s; //Need to add feature that instantly puts the element at the first available spot on the list.
    } else { 
        for (int j = i; j < array.length; j++) { //Can't use >= i
            array[j + 1] = array[j];

            if (j == array.length - 1) { 
                break;
            } 
        }
        array[i] = s;
4

3 に答える 3

1

Well, arrays are not dynamic, so if you have an array that has size 3 you cannot add anything to it unless you create a new array that has size of oldArray.length+1 and then populate it with new data.

于 2013-11-13T14:29:40.757 に答える
0
public static int[] addAtIndex(int[] a, int index, int value) {
 int[] newArr = new int[a.length + 1];
 int temp;
 for (int j = 0; j < a.length + 1; j++) {
  if (j < index) {
   newArr[j] = a[j];
  } else if (j == index) {
   //copy value at index to temp so that value added at specific index can be shifted right
   temp = a[j];
   newArr[j] = value;
   newArr[j + 1] = temp;
  } else {
   newArr[j] = a[index];
   index++;
  }
 }
 return newArr;
}
于 2019-02-16T16:05:40.093 に答える