Java – fill an array using java.util.Arrays

Fill all values in an array

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] arr = new int[10];
    Arrays.fill(arr, 1);
    for (int v: arr) {
      System.out.println(v);
    }
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   7953
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Fill range in an array

import java.util.Arrays;

public class Main2 {
  public static void main(String[] args) {
    int[] arr = new int[10];
    Arrays.fill(arr, 1);
    Arrays.fill(arr, 0, 5, 2); // fill first five values with 2
    for (int v: arr) {
      System.out.println(v);
    }
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   7965
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments