Inserção, exclusão por índice e deslocamento
Insira elementos em uma nova matriz, exclua por índice com deslocamento para a esquerda e pratique verificações seguras dos limites.
Inserção, exclusão por índice e deslocamento é uma aula grátis de Java Academy no CoddyKit. Esta é a aula 3 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Java Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Java Academy inclui 3 aulas no total.
Visão geral da inserção
Inserir em um vetor simples geralmente cria um novo vetor com um espaço extra. Copie os elementos anteriores à posição, coloque o novo valor e depois copie o restante deslocado uma posição.
Inserir em um novo vetor
Insira no índice i em um novo vetor:
public class Main {
// Method to insert a value at a given index
static int[] insertAt(int[] a, int i, int val) {
// Create a new array, one element larger
int[] b = new int[a.length + 1];
// Copy elements before the insertion index
for (int p = 0; p < i; p = p + 1) {
b[p] = a[p];
}
// Insert the new value at position i
b[i] = val;
// Copy the rest of the elements after position i
for (int p = i; p < a.length; p = p + 1) {
b[p + 1] = a[p];
}
return b;
}
public static void main(String[] args) {
// Example array
int[] a = {5, 8, 9, 12};
// Insert 99 at index 2 (between 8 and 9)
int[] b = insertAt(a, 2, 99);
// Print new array
System.out.print("Array after insertion: ");
for (int x : b) {
System.out.print(x + " ");
}
}
}
Excluir e deslocar
Exclua por índice deslocando os elementos para a esquerda e limpando a última célula:
public class Main {
// Method to delete an element at index k
static void deleteAt(int[] a, int k) {
// Shift elements to the left, starting from index k
for (int i = k; i < a.length - 1; i = i + 1) {
a[i] = a[i + 1];
}
// Clear the last element (since it's now duplicated)
a[a.length - 1] = 0;
}
public static void main(String[] args) {
// Example array
int[] a = {5, 8, 9, 12, 15};
// Delete element at index 2 (value = 9)
deleteAt(a, 2);
// Print updated array
System.out.print("Array after deletion: ");
for (int x : a) {
System.out.print(x + " ");
}
}
}
Verificação de limites
A verificação de limites ajuda a evitar erros em tempo de execução. O índice válido para n elementos é 0..n-1. Para inserir, i válido é 0..n.
public class Main {
// Insert a value at a given index
static int[] insertAt(int[] a, int i, int val) {
// Validate index (0 ≤ i ≤ a.length is allowed for insert)
if (i < 0 || i > a.length) {
throw new IllegalArgumentException("bad index");
}
int[] b = new int[a.length + 1];
for (int p = 0; p < i; p++) b[p] = a[p];
b[i] = val;
for (int p = i; p < a.length; p++) b[p + 1] = a[p];
return b;
}
// Delete a value at a given index
static void deleteAt(int[] a, int k) {
// Validate index (0 ≤ k < a.length is required for delete)
if (k < 0 || k >= a.length) {
throw new IllegalArgumentException("bad index");
}
for (int i = k; i < a.length - 1; i++) {
a[i] = a[i + 1];
}
a[a.length - 1] = 0; // clear the last slot
}
public static void main(String[] args) {
int[] a = {5, 8, 9, 12};
// Test insert
int[] b = insertAt(a, 2, 99);
System.out.print("After insert: ");
for (int x : b) System.out.print(x + " ");
System.out.println();
// Test delete
deleteAt(b, 3);
System.out.print("After delete: ");
for (int x : b) System.out.print(x + " ");
}
}
Excluir criando um novo vetor
Crie uma cópia menor que ignore o índice k:
public class Main {
// Method to create a new array without the element at index k
static int[] without(int[] a, int k) {
// Validate index
if (k < 0 || k >= a.length) {
throw new IllegalArgumentException("bad index");
}
// New array has one fewer element
int[] b = new int[a.length - 1];
// Copy elements before k
for (int p = 0; p < k; p = p + 1) {
b[p] = a[p];
}
// Copy elements after k (shift left by one)
for (int p = k + 1; p < a.length; p = p + 1) {
b[p - 1] = a[p];
}
return b;
}
public static void main(String[] args) {
int[] a = {5, 8, 9, 12, 15};
// Remove element at index 2 (value = 9)
int[] b = without(a, 2);
// Print original
System.out.print("Original array: ");
for (int x : a) System.out.print(x + " ");
System.out.println();
// Print new array
System.out.print("Array without index 2: ");
for (int x : b) System.out.print(x + " ");
}
}
Demonstração de inserção e exclusão
Execute: veja a inserção em um novo vetor, a exclusão no próprio vetor com deslocamento para a esquerda e a exclusão por cópia.
public class Main {
static int[] insertAt(int[] a, int i, int val) {
if (i < 0 || i > a.length) throw new IllegalArgumentException("bad index");
int[] b = new int[a.length + 1];
for (int p = 0; p < i; p = p + 1) b[p] = a[p];
b[i] = val;
for (int p = i; p < a.length; p = p + 1) b[p + 1] = a[p];
return b;
}
static void deleteAtShift(int[] a, int k) {
if (k < 0 || k >= a.length) throw new IllegalArgumentException("bad index");
for (int i = k; i < a.length - 1; i = i + 1) {
a[i] = a[i + 1];
}
a[a.length - 1] = 0;
}
static int[] without(int[] a, int k) {
if (k < 0 || k >= a.length) throw new IllegalArgumentException("bad index");
int[] b = new int[a.length - 1];
for (int p = 0; p < k; p = p + 1) b[p] = a[p];
for (int p = k + 1; p < a.length; p = p + 1) b[p - 1] = a[p];
return b;
}
static String join(int[] a) {
String s = "";
for (int i = 0; i < a.length; i = i + 1) {
s = s + a[i] + (i + 1 < a.length ? " " : "");
}
return s;
}
public static void main(String[] args) {
int[] a = {10, 20, 30, 40};
System.out.println("a = " + join(a));
int[] b = insertAt(a, 2, 99);
System.out.println("insertAt(2) = " + join(b));
deleteAtShift(a, 1);
System.out.println("deleteAt(1) = " + join(a));
int[] c = without(b, 3);
System.out.println("without(3) = " + join(c));
}
}
Verificação de exclusão e deslocamento
Verificação rápida: qual trecho exclui no índice k deslocando os elementos para a esquerda e limpando o último espaço?
Recapitulação e próximo passo
Recapitulação: você inseriu usando um novo vetor, excluiu deslocando para a esquerda e criou cópias menores. Sempre verifique os limites.
Próximo passo: avance para vetores de objetos e algoritmos simples, como a contagem de frequências.
Perguntas Frequentes
A aula “Inserção, exclusão por índice e deslocamento” é grátis?
Sim — o texto completo de “Inserção, exclusão por índice e deslocamento” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Java Academy, atualize para CoddyKit PRO. O curso de Java Academy inclui 3 aulas no total.
O que vou aprender em “Inserção, exclusão por índice e deslocamento”?
Insira elementos em uma nova matriz, exclua por índice com deslocamento para a esquerda e pratique verificações seguras dos limites. Você pratica Java Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Java Academy?
Nenhuma experiência prévia é necessária. Java Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 3.
Quanto tempo leva a aula “Inserção, exclusão por índice e deslocamento”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Java Academy?
Sim. Cada aula de Java Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Noções básicas de matrizes e iteração
- Pesquisa, mínimo/máximo e inversão
- Inserção, exclusão por índice e deslocamento