System.arraycopy
è più performante ma difficile da ottenere a causa dei calcoli degli indici. Meglio attenersi alla risposta jrad o ArrayList
se non si dispone di requisiti di prestazione.
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;
}
E JUnit4 test per verificare che funzioni come previsto.
@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));
}
Non è possibile spostare gli indici per array in Java . Gli array sono di dimensioni fisse. Crea un nuovo array con i valori desiderati e assegna il riferimento 'a' al nuovo array. – kosa
Compiti? Se è così, taggalo come tale. –
Ora è troppo tardi perché esiste già una risposta a codice completo. –