자바 Arrays.fill()

Jmnote (토론 | 기여)님의 2021년 4월 14일 (수) 18:45 판 (→‎개요)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요[ | ]

Arrays.fill()
기본 채우기
import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
        int[] arr = new int[] {1, 2, 3, 4, 5};
        Arrays.fill(arr, 100);
        System.out.println( Arrays.toString(arr) ); // [100, 100, 100, 100, 100]
    }
}
구간 지정하여 채우기
import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
        int[] arr = new int[] {1, 2, 3, 4, 5};
        Arrays.fill(arr, 2, 4, 100);
        System.out.println( Arrays.toString(arr) ); // [1, 2, 100, 100, 5]
    }
}
2차원 배열 채우기
import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
        int[][] arr = new int[3][5];
        for(int[] row: arr) {
            Arrays.fill(row, 10);
        }
        for(int[] row: arr) {
            System.out.println( Arrays.toString(row) );
        }
    }
}
3차원 배열 채우기
import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
        int[][][] arr = new int[3][5][2];
        for(int[][] row2: arr) {
            for(int[] row: row2) {
                Arrays.fill(row, 10);
            }
        }
        for(int[][] row2: arr) {
            for(int[] row: row2) {
                System.out.print( Arrays.toString(row) );
            }
            System.out.println();
        }
    }
}

2 같이 보기[ | ]

3 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}