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]
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024