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 split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023