How to populate arrays in Java?

I know how to do this normally, but I can swear that you can fill out the form as [0] = {0,0,0,0}; How do you do this? I tried google but I got nothing.

+65
java arrays
Feb 23 '09 at 8:02
source share
8 answers

You can also do this as part of the declaration:

int[] a = new int[] {0, 0, 0, 0}; 
+54
Feb 23 '09 at 8:05
source share

Check out the Arrays.fill methods.

 int[] array = new int[4]; Arrays.fill(array, 0); 
+227
Feb 23 '09 at 8:04
source share

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

+15
Feb 23 '09 at 8:03
source share

In Java-8, you can use IntStream to create the stream of numbers you want to repeat, and then convert to an array. This approach gives 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 elements you want to repeat tot, and the repeating value.

Demo version

+9
Jun 26 '15 at 16:45
source share

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

For example, a String array can be declared either:

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

Primitives can also be initialized in the same way:

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

Or an array from Object :

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

All details about arrays in Java are written out in Chapter 10: Arrays in the Java Language Specification, third edition .

+5
Feb 23 '09 at 8:09
source share
 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]+" "); } 

Exit

 5 6 9 2 10 0 0 0 0 0 
+5
Dec 25 '15 at 2:44
source share

Array elements in Java are initialized with default values ​​at creation. For numbers, this means that they are initialized to 0, for links they are zero, and for logical ones 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 populate arrays with arithmetic series, as in some scripting languages.

+2
Feb 23 '09 at 8:09
source share
 int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 
-2
Mar 02 '16 at 19:08
source share



All Articles