Is it possible to create an empty array without specifying the size?
For example, I created:
String[] a = new String[5];
Can we create the above string array without the size?
To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.
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.
Array elements are initialized to 0 if they are a numeric type ( int or double ), false if they are of type boolean , or null if they are an object type like String .
If you are going to use a collection that you don't know the size of in advance, there are better options than arrays.
Use a List<string>
instead - it will allow you to add as many items as you need and if you need to return an array, call ToArray()
on the variable.
var listOfStrings = new List<string>(); // do stuff... string[] arrayOfStrings = listOfStrings.ToArray();
If you must create an empty array you can do this:
string[] emptyStringArray = new string[0];
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