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.
int[] myNumbers = new int[size];
Arrays.fill(myNumbers, 0);
see http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html
int[] MyNumbers = new int[number_of_elements];
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With