In the current code base that I'm working on I find myself needing to initialise many empty String[] of different lengths.
As of now, they are always initialised in the following way:
String[] a = new String[]{"","","","","","","","",""} // etc...
Although this is a simple one line solution, my personal preference is that it's rather ugly.
I was just wondering if anyone is aware of any existing API/Utility that offers a method where an array of empty strings can be initialised more elegantly. I was thinking something along the lines of:
StringUtils.*initialiseEmptyArray*(int size);
Does anyone know of any such method?
I can always write my own if need be, just didn't want to re-invent the wheel if its already been done.
Thanks
However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use: private static final String[] EMPTY_ARRAY = new String[0];
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 String Array is initialized at the same time as it is declared. You can also initialize the String Array as follows: String[] strArray = new String[3]; strArray[0] = “one”; strArray[1] = “two”; strArray[2] = “three”; Here the String Array is declared first.
You can use Arrays.fill
method: -
Arrays.fill(a, "");
Using Arrays.fill:
String[] a = new String[9]; Arrays.fill(a, "");
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