此功能应该在所选索引处添加一个元素,并将数组元素中的所有其他元素向下推。所以,例如,假设我有以下数组:
[0] = zero
[1] = one
[2] = two
如果我在索引0处添加另一个名为NEWZERO的元素,则数组必须如下所示:
[0] = NEWZERO
[1] = zero
[2] = one
[3] = two
但目前我正在获得IndexOutOfBounds异常,但它不起作用。
P.S。我不想使用内置的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;
答案 0 :(得分:3)
试试这个
public void insert(int i, String s) {
String[] newArr = new String[array.length + 1];
for (int j = 0; j < array.length; j++) {
if(j < i){
newArr[j] = array[j];
} else if(j == i){ // '==' insted of '='
newArr[j] = s;
} else {
newArr[j+1] = array[i];
}
}
array = newArr;
}
答案 1 :(得分:1)
好吧,数组不是动态的,所以如果你有一个大小为3的数组,除非你创建一个大小为oldArray.length + 1的新数组然后用新数据填充它,否则你不能添加任何数组。 / p>
答案 2 :(得分: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;
}