System.arraycopy
hoạt động hiệu quả hơn nhưng khó để có được quyền do tính toán chỉ mục. Tốt hơn dính với câu trả lời jrad hoặc ArrayList
nếu bạn không có yêu cầu hiệu suất.
public static int[] insert(
int[] array, int elementToInsert, int index) {
int[] result = new int[array.length + 1];
// copies first part of the array from the start up until the index
System.arraycopy(
array /* src */,
0 /* srcPos */,
result /* dest */,
0 /* destPos */,
index /* length */);
// copies second part from the index up until the end shifting by 1 to the right
System.arraycopy(
array /* src */,
index /* srcPos */,
result /* dest */,
index + 1 /* destPos */,
array.length - index /* length */);
result[index] = elementToInsert;
return result;
}
Và kiểm tra JUnit4 để kiểm tra xem có hoạt động như mong đợi không.
@Test
public void shouldInsertCorrectly() {
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{1, 3}, 2, 1));
Assert.assertArrayEquals(
new int[]{1}, insert(new int[]{}, 1, 0));
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{2, 3}, 1, 0));
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{1, 2}, 3, 2));
}
Bạn không thể thay đổi chỉ số cho mảng trong Java . Mảng là kích thước cố định. Tạo mảng mới với các giá trị bạn muốn và gán tham chiếu 'a' cho mảng mới. – kosa
Bài tập về nhà? Nếu có, hãy gắn thẻ như vậy. –
Quá muộn vì đã có câu trả lời đầy đủ. –