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?
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.)
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