Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize String[] with empty strings

I want to create a String array containing multiple empty strings.

String[] array = {"", "", "", "", ""};

In python we could achieve this simply with this code [""] * 5. Is there something similar for java?


1 Answers

Nothing syntactic, no.

At an API level, there's Arrays.fill, but sadly it doesn't return the array you pass it, so you can't use it in the initializer, you have to use it after:

String[] array = new String[5];
Arrays.fill(array, "");

You could always roll-your-own static utility method of course.

public static <T> T[] fill(T[] array, T value) {
    Arrays.fill(array, value);
    return array;
}

then

String[] array = YourNiftyUtilities.fill(new String[5], "");

(Obviously, it would probably be dodgy to do that with mutable objects, but it's fine with String.)

like image 189
T.J. Crowder Avatar answered May 15 '26 21:05

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!