tags:

views:

2941

answers:

7

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.

+3  A: 

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

Zach Scrivena
+14  A: 

Check out the Arrays.fill methods.

int[] array = new int[4];
Arrays.fill(array, 0);
cdmckay
+1 because I didn't know about Arrays.fill() method. I always did it with a for loop. :D
Spoike
+10  A: 

You can also do it as part of the declaration:

int[] a = new int[] {0, 0, 0, 0};
Chad Birch
This is what I was thinking of, thank you!
William
int[] a = new int[4] would accomplish the same thing, since 0 is the default value.
Zach Scrivena
Or int[] a = {0, 0, 0, 0}; . You only need the new int[] if the constant is not immediately used in a declaration.
starblue
+3  A: 

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.

coobird
+1  A: 

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.

staffan
+1  A: 

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

Daren Thomas
A: 

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 !

elektro
You need to ask a new question. Here you have merely added an *answer* to an existing question that was months old. Nobody answered you because nobody noticed your question!
Todd Owen