一种在Java中初始化空String数组的优雅方法

时间:2022-04-25 21:29:50

In the current code base that I'm working on I find myself needing to initialise many empty String[] of different lengths.

在我正在处理的当前代码库中,我发现自己需要初始化许多不同长度的空String []。

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:

我只是想知道是否有人知道任何现有的API / Utility提供了一种方法,其中可以更优雅地初始化空字符串数组。我在思考以下几点:

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

谢谢

2 个解决方案

#1


34  

You can use Arrays.fill method: -

你可以使用Arrays.fill方法: -

Arrays.fill(a, "");

#2


16  

Using Arrays.fill:

使用Arrays.fill:

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

#1


34  

You can use Arrays.fill method: -

你可以使用Arrays.fill方法: -

Arrays.fill(a, "");

#2


16  

Using Arrays.fill:

使用Arrays.fill:

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