How to remove all occurrences of a value in array of integers with Java

1 Answer

0 votes
import java.util.Arrays;

class program {
    public static int[] removeElements(int[] arr, int value) {
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != value) {
                arr[index++] = arr[i];
            }
        }
        return Arrays.copyOf(arr, index);
    }

    public static void main(String[] args) {
        int[] array = {1, 3, 8, 23, 8, 99, 8, 100, 7};
        int value = 8;
        
        array = removeElements(array, value);
        
        System.out.println(Arrays.toString(array));
    }
}



 
/*
run:
 
[1, 3, 23, 99, 100, 7]
 
*/

 



answered Apr 23, 2024 by avibootz

Related questions

2 answers 246 views
1 answer 113 views
3 answers 171 views
1 answer 158 views
1 answer 182 views
...