Java >> Tutoriel Java >  >> Java

Programme Java pour supprimer l'entier spécifié d'un tableau

Dans ce tutoriel, nous allons apprendre à supprimer un élément spécifique d'un tableau. Le moyen le plus simple de supprimer un élément dans un tableau consiste à décaler les éléments d'un index vers la gauche à partir de l'endroit où nous voulons supprimer l'élément. Mais avant d'aller plus loin, si vous n'êtes pas familier avec les concepts du tableau, alors consultez l'article Tableaux en Java.

Saisie : 5 9 8 3 2 6 7

Sortie : Elément à supprimer :8

Tableau :5 9 3 2 6 7

Programme 1 :Comment supprimer un élément spécifique d'un tableau

Dans cette approche, nous parcourrons tous les éléments et décalerons les éléments vers la gauche d'un indice partout où se trouve l'élément à supprimer.

Algorithme

  1. Commencer
  2. Déclarer un tableau
  3. Initialiser le tableau.
  4. Déclarez l'élément à supprimer.
  5. Utiliser une boucle for pour parcourir tous les éléments du tableau.
  6. Si l'élément est trouvé, commencez à déplacer les éléments après cet index vers la gauche d'un élément.
  7. Maintenant, imprimez le tableau mis à jour.
  8. Arrêter

Vous trouverez ci-dessous le code correspondant.

Le programme ci-dessous montre comment supprimer un élément spécifique d'un tableau en parcourant tous les éléments.

/*Java Program to delete an element from an Array*/
import java.util.Arrays;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int n;    //Array Size Declaration
        System.out.println("Enter the number of elements :");
        n=sc.nextInt();    //Array Size Initialization
        
        Integer arr[]=new Integer[n];    //Array Declaration
        System.out.println("Enter the elements of the array :");
        for(int i=0;i<n;i++)     //Array Initialization
        {
            arr[i]=sc.nextInt();
        }
        System.out.println("Enter the element you want to remove ");
        int elem = sc.nextInt();
    
    for(int i = 0; i < arr.length; i++)
    {
      if(arr[i] == elem)   //If element found
      {
        // shifting elements
        for(int j = i; j < arr.length - 1; j++)
        {
            arr[j] = arr[j+1];
        }
        break;
      }
    }
      
       System.out.println("Elements after deletion " );
       for(int i = 0; i < arr.length-1; i++)
       {
             System.out.print(arr[i]+ " ");
       }  
    }
}


Entrez le nombre d'éléments :10
Entrez les éléments du tableau :
1 2 3 4 5 6 7 8 9 10
Entrez l'élément que vous souhaitez supprimer
5
Éléments après suppression
1 2 3 4 6 7 8 9 10

Programme 2 :Comment supprimer un élément spécifique d'un tableau

Dans cette approche, nous utiliserons l'API Collection pour supprimer un élément d'un tableau. Tout d'abord, nous allons convertir un tableau en une liste de tableaux, puis supprimer l'élément spécifique. Après la suppression de l'élément, nous reconvertirons la liste de tableaux en tableau.

Algorithme

  1. Commencer
  2. Déclarer un tableau
  3. Initialiser le tableau.
  4. Déclarez l'élément à supprimer.
  5. Utiliser une boucle for pour parcourir tous les éléments du tableau.
  6. Si l'élément est trouvé, appelez une méthode distincte pour supprimer l'élément.
  7. Convertir le tableau en une liste de tableaux.
  8. Maintenant, supprimez l'élément.
  9. Reconvertissez-le en tableau.
  10. Maintenant, imprimez le tableau mis à jour.
  11. Arrêtez.

Vous trouverez ci-dessous le code correspondant.

Le programme ci-dessous montre comment supprimer un élément spécifique d'un tableau en utilisant l'API Collection fournie par le langage Java.

/*Java Program to delete an element in an Array*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class RemoveElement 
{
  public static void main(String[] args) 
  {
    Scanner in = new Scanner(System.in);
     
          int n;                               // Array Size Declaration
         System.out.println("Enter the number of elements :");
          n=in.nextInt();                // Array Size Initialization
        
        Integer arr[]=new Integer[n];    // Array Declaration
        System.out.println("Enter the elements of the array :");
        for(int i=0;i<n;i++)                   // Array Initialization
        {
            arr[i]=in.nextInt();
        }
    
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();          //Initializing Element
        
    System.out.println("Original Array " + Arrays.toString(arr));        
    for(int i = 0; i < arr.length; i++)
    {
      if(arr[i] == elem)
      {
               arr = removeElementUsingCollection(arr, i);
               break;
      }
    }
    System.out.println("Array after removal of Element -- " );
    for(int i = 0; i < arr.length; i++)
    {
           System.out.print(" " + arr[i]);
    }
       
  }  


    static Integer[] removeElementUsingCollection( Integer[] arr, int index )
    {
      List<Integer> tempList = new ArrayList<Integer>(Arrays.asList(arr));
      tempList.remove(index);
      return tempList.toArray(new Integer[0]);
    }
}


Saisir le nombre d'éléments :10
Saisir les éléments du tableau :
1 2 3 4 5 6 7 8 9 10
Saisir l'élément à supprimer :8
Matrice d'origine
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Matrice après suppression de l'élément --
1 2 3 4 5 6 7 9 10


Balise Java