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?
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.)
array[0].property = value to mean that array[1].property now has that value (because array[0] and array[1] refer to the same object). But Strings are immutable (modulo unreasonable games with reflection) so there's no such concern here.With Java 8, you have a not-so-concise, yet better-than-repeated-literals idiom:
// will create a String[] with 42 blank Strings
String[] test = Stream
// generate an infinite stream with a supplier for empty strings
.generate(() -> "")
// make the stream finite to a given size
.limit(42)
// convert to array with the given generator function to allocate the array
.toArray(String[]::new);
You can use the fill method from the Arrays class.
String[] test = new String[10];
Arrays.fill(test, "");
Arrays, no?import java.util.Arrays;You could try cycle:
String[] array = new String[5];
for (int i = 0; i < 5; i++)
array[i] = "";
5 in two different places.array.length.