0 votes
1.4k views
in Java by
How to remove element from array in java? Plese give an example.

1 Answer

0 votes
by

Please see the following example. In this example we have an array which contains 10,50,20,70,60,25,18 elements and remove 20 from this array.

package com;

public class RemoveElementFromArray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int arr[] = {10,50,20,70,60,25,18};
        int removeElement = 20;
        System.out.println("######### Before Removing ######### ");
        for(int i=0; i < arr.length-1; i++){
            System.out.print(arr[i]+", ");
        }
        doRemove(arr, removeElement);
        System.out.println("\n######### After Removing ######### ");
        for(int i=0; i < arr.length-2; i++){
            System.out.print(arr[i]+", ");
        }
    }

    private static void doRemove(int[] arr, int removeElement) {
        for(int i=0; i < arr.length-1; i++){
            if(arr[i] == removeElement){
                for(int j=i; j < arr.length - 2; j++){
                    arr[j] = arr[j + 1];
                }
                break;
            }
        }
    }

}

Output:
######### Before Removing #########
10, 50, 20, 70, 60, 25,
######### After Removing #########
10, 50, 70, 60, 25,

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...