An elegant way of initialising an empty String arr

2020-04-01 08:45发布

问题:

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

回答1:

You can use Arrays.fill method: -

Arrays.fill(a, "");


回答2:

Using Arrays.fill:

String[] a = new String[9];
Arrays.fill(a, "");