java removes an element from an array

  • 2020-05-30 20:03:27
  • OfStack

Examples are as follows:


package org.company.project.test;

import java.util.Arrays;

import java.util.Scanner;

public class ArraysDelete { public static void main(String[] args) {

// Delete something from the array 1 Method of element: 

// The final 1 Instead of the specified element, the array is shrunk 

Scanner sc =new Scanner(System.in);

int[] arr = new int[]{1,2,4,5,9,8,0};

System.out.println(Arrays.toString(arr));

System.out.println(" Please enter the number of elements to delete: ");

int n = sc.nextInt(); sc.close();

// The final 1 Element replaces the specified element 

arr[n-1] = arr[arr.length-1];

// Array shrinkage capacity 

arr = Arrays.copyOf(arr, arr.length-1);

System.out.println(Arrays.toString(arr));

} }

Operation results:

[1, 2, 4, 5, 9, 8, 0]

Please enter the number of elements to delete:

3

[1, 2, 0, 5, 9, 8]


Related articles: