Possible Duplicate:
How do I quicky fill an array with a specific value?
Is there a way to initialize an integer array with a single value like -1 without having to explicitly assign each item?
Basically, if I have
int[] MyIntArray = new int[SomeCount];
All items are assigned 0 by default. Is there a way to change that value to -1 without using a loop? or assigning explicitly each item using {}?
The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
There are various ways in which you can declare an array in Java: float floatArray[]; // Initialize later int[] integerArray = new int[10]; String[] array = new String[] {"a", "b"};
int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();
You could use the Enumerable.Repeat method
int[] myIntArray = Enumerable.Repeat(1234, 1000).ToArray()
will create an array of 1000 elements, that all have the value of 1234.
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