3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

初心者のころには知らなかったJavaで配列の一括初期化する方法

Posted at

配列の一括初期化

配列の要素を0で全初期化する方法
(C言語で言うmemset的なもの)

Arrays.fill(配列, 初期化値)

import java.util.Arrays;
public class HelloWorld {
    public static void main (String[] args) {
        int[] intArray = new int[10];
        Arrays.fill(intArray, 0); // 第二引数で初期化値を指定する
        System.out.println(Arrays.toString(intArray));
    }
}

// => [0, 0, 0, ...]

この方法は文字列にも対応できる

import java.util.Arrays;
public class HelloWorld {
    public static void main (String[] args) {
        String[] str = new String[5];
        Arrays.fill(str, "_"); // 第二引数で初期化値を指定する
        System.out.println(Arrays.toString(str));
    }
}

// => ["_", "_", "_", ...]

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?