logo

예제가 포함된 Java의 Arrays.fill()

java.util.Arrays.fill() 방법은 java.util.Arrays 클래스 . 이 메소드는 지정된 배열의 지정된 범위에 있는 각 요소에 지정된 데이터 유형 값을 할당합니다.

 Syntax: // Makes all elements of a[] equal to 'val' public static void fill (int[] a, int val) // Makes elements from from_Index (inclusive) to to_Index // (exclusive) equal to 'val' public static void fill (int[] a, int from_Index, int to_Index, int val) This method doesn't return any value.>
 Exceptions it Throws: IllegalArgumentException - if from_Index>to_Index ArrayIndexOutOfBoundsException - from_Index a.length>'>인 경우 

예:



컴퓨터 네트워크의 네트워크 계층

전체 배열을 채울 수 있습니다.








// Java program to fill a subarray of given array> import> java.util.Arrays;> > public> class> Main> {> >public> static> void> main(String[] args)> >{> >int> ar[] = {>2>,>2>,>1>,>8>,>3>,>2>,>2>,>4>,>2>};> > >// To fill complete array with a particular> >// value> >Arrays.fill(ar,>10>);> >System.out.println(>'Array completely filled'> +> >' with 10 '> + Arrays.toString(ar));> >}> }>

>

산출:

Array completely filled with 10 [10, 10, 10, 10, 10, 10, 10, 10, 10]>

배열의 일부를 채울 수 있습니다.




// Java program to fill a subarray array with> // given value.> import> java.util.Arrays;> > public> class> Main> {> >public> static> void> main(String[] args)> >{> >int> ar[] = {>2>,>2>,>2>,>2>,>2>,>2>,>2>,>2>,>2>};> > >// Fill from index 1 to index 4.> >Arrays.fill(ar,>1>,>5>,>10>);> > >System.out.println(Arrays.toString(ar));> >}> }>

>

>

산출:

[2, 10, 10, 10, 10, 2, 2, 2, 2]>

다차원 배열을 채울 수 있습니다
루프를 사용하여 다차원 배열을 채울 수 있습니다.
1) 2D 배열 채우기

자바의 기본 데이터 유형




// Java program to fill a multidimensional array with> // given value.> import> java.util.Arrays;> > public> class> Main> {> >public> static> void> main(String[] args)> >{> >int> [][]ar =>new> int> [>3>][>4>];> > >// Fill each row with 10.> >for> (>int>[] row : ar)> >Arrays.fill(row,>10>);> > >System.out.println(Arrays.deepToString(ar));> >}> }>

>

>

산출:

[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]>

2) 3차원 배열 채우기




// Java program to fill a multidimensional array with> // given value.> > import> java.util.Arrays;> > class> GFG {> > >public> static> void> main(String[] args) {> >int>[][][] ar =>new> int>[>3>][>4>][>5>];> > >// Fill each row with -1.> >for> (>int>[][] row : ar) {> >for> (>int>[] rowColumn : row) {> >Arrays.fill(rowColumn, ->1>);> >}> >}> > >System.out.println(Arrays.deepToString(ar));> >}> }>

>

>

산출:

[[[-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]], [[-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]], [[-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]]]>