How do I clear the content of an array?

In this example you’ll learn how to clear or reset the content of an array. We can use the java.util.Arrays.fill() method to replace to content of each element in the array. In the example below we create two arrays, names and numbers array. We initialize these arrays with some values and then clear the value by assigning null to each element of the array using the Arrays.fill() method.

package org.kodejava.util;

import java.util.Arrays;

public class ArrayClear {
    public static void main(String[] args) {
        String[] names = {"Alice", "Bob", "Carol"};
        System.out.println("Names = " + Arrays.toString(names));

        // Replace the contents of the names array to null for each array
        // element.
        Arrays.fill(names, null);
        System.out.println("Names = " + Arrays.toString(names));

        Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println("Numbers = " + Arrays.toString(numbers));

        // Replace the contents of the numbers array to null for each
        // array element.
        Arrays.fill(numbers, null);
        System.out.println("Numbers = " + Arrays.toString(numbers));
    }
}

The output of the code snippet:

Names = [Alice, Bob, Carol]
Names = [null, null, null]
Numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Numbers = [null, null, null, null, null, null, null, null, null, null]
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.