Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An elegant way of initialising an empty String array in Java

Tags:

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

like image 237
JoshDavies Avatar asked Jan 21 '13 20:01

JoshDavies


People also ask

How do you initialize an empty string array in Java?

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];

Can you initialize an empty array in Java?

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.

How do I initialize a string array?

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.


2 Answers

You can use Arrays.fill method: -

Arrays.fill(a, ""); 
like image 57
Rohit Jain Avatar answered Oct 17 '22 07:10

Rohit Jain


Using Arrays.fill:

String[] a = new String[9]; Arrays.fill(a, ""); 
like image 29
Reimeus Avatar answered Oct 17 '22 09:10

Reimeus