views:

350

answers:

4

I have an array of integers in Java that is initialized as follows:

public int MyNumbers[] = {0,0,0,0};

I would like to, however, initialize the array to a variable-length number of zeroes.

private int number_of_elements = 4;
public int MyNumbers[] = {0} * number_of_elements; // ????

I am clueless how to do this being new to Java coming from C. Any suggestions?

EDIT

I know I could use a for loop, but I hoping there was a simple way to do it.

+2  A: 
int[] MyNumbers = new int[number_of_elements];
Trevor Harrison
I think the zero in the example code is meant as an example, while this one-liner will create the array filled with zeroes, it still doesn't enable the OP to fill it with another, arbitrary value.
laginimaineb
+7  A: 
int[] myNumbers = new int[size];
Arrays.fill(myNumbers, 0);

see http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html

laginimaineb
Thanks, dude! Am I right in assuming the import line is just `java.util.Arrays`?
daveslab
Yup. One thing to note, though, is that according to the source of Arrays.java (JDK 6) the above function does indeed use a for loop. But one day it might just as easily change that behaviour to use something more low level such as a memset (through JNI).
laginimaineb
I would trust the JVM to replace this code with faaaaaast code. Typically loops are unrolled by the JVM, mebbe her it even optimized it to a memset. In Java, never optimize at the code level!
Adrian
+2  A: 

Alternatively you could use ArrayList so that you don't need to worry about the size beforehand. It will dynamically expand the internal array whenever needed.

List<Integer> numbers = new ArrayList<Integer>();
numbers.add(0);
numbers.add(2);
// ...

Here's a tutorial to learn more about the Collections API, which ArrayList is part of.

BalusC
+1 For use of ArrayList. That's exactly what I was thinking he should do.
WillMatt
+1 "Prefer lists over arrays"
Helper Method
+1  A: 
int[] MyNumbers = new int[number_of_elements];

Since this is an array of int the array elements will get the default value for int's in Java of 0 automatically.

If this were an array of Integer objects then you would have to fill array after creating it as the default value for an object reference is null. To set default values in an Object array you can do the following:

Integer[] MyNumbers = new Integer[number_of_elements];
java.util.Arrays.fill(MyNumbers, new Integer(0));

The same technique could of course be used to initialize the int array to values other than zero like so:

int[] MyNumbers = new int[number_of_elements];
java.util.Arrays.fill(MyNumbers, 1);
Tendayi Mawushe
nitpick: when you fill the Integer array, you should probably use 'Integer.valueOf()' instead of 'new Integer()' since that will make use of the Integer cache (see http://tech.puredanger.com/2007/02/01/valueof/ for an interesting read)
laginimaineb