Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable-sized Array Initialization in Java

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.

like image 698
daveslab Avatar asked Jan 07 '10 20:01

daveslab


4 Answers

int[] myNumbers = new int[size];
Arrays.fill(myNumbers, 0);

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

like image 154
laginimaineb Avatar answered Oct 06 '22 19:10

laginimaineb


int[] MyNumbers = new int[number_of_elements];
like image 40
Trevor Harrison Avatar answered Oct 06 '22 19:10

Trevor Harrison


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.

like image 24
BalusC Avatar answered Oct 06 '22 19:10

BalusC


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);
like image 2
Tendayi Mawushe Avatar answered Oct 06 '22 21:10

Tendayi Mawushe