I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful.
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, 0);
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.
The term you are looking for is: (static) array initialization.
This could pop up pretty much on top: http://www.janeg.ca/scjp/lang/arrays.html
hello everyone, i need your help! i would like to fill arrays of char with letters (all the alphabetics letters) so i need a FOR loop but how can i switch from a letter to another?! I mean there's no function that allows me to get letters by giving the ascii code for example??
Thanks a lot !