如何在 Java 中填充数组?

我知道如何正常填写,但我可以发誓,你可以像 a [0] = {0,0,0,0}那样填写?我试过谷歌,但没有任何有用的信息。

332466 次浏览

Arrays.fill(). The method is overloaded for different data types, and there is even a variation that fills only a specified range of indices.

Check out the Arrays.fill methods.

int[] array = new int[4];
Arrays.fill(array, 1); // [1, 1, 1, 1]

You can also do it as part of the declaration:

int[] a = new int[] {0, 0, 0, 0};

An array can be initialized by using the new Object {} syntax.

For example, an array of String can be declared by either:

String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};

Primitives can also be similarly initialized either by:

int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};

Or an array of some Object:

Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};

All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.

Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.

To fill the array with something else you can use Arrays.fill() or as part of the declaration

int[] a = new int[] {0, 0, 0, 0};

There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.

In Java-8 you can use IntStream to produce a stream of numbers that you want to repeat, and then convert it to array. This approach produces an expression suitable for use in an initializer:

int[] data = IntStream.generate(() -> value).limit(size).toArray();

Above, size and value are expressions that produce the number of items that you want tot repeat and the value being repeated.

Demo.

Arrays.fill(arrayName,value);

in java

int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}

Output

5 6 9 2 10
0 0 0 0 0
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};