public static void printStrings(String... strings) for (String s : strings) System.out.println(s);
To call a varargs method, you can either pass individual arguments separated by commas, or pass an array of the same type as the varargs parameter. For example, both of the following calls are valid:
printStrings("Hello", "World"); printStrings(new String[] "Hello", "World");
However, there is a subtle difference between these two calls. When you pass individual arguments, the compiler automatically creates an array for you and passes it to the method. This is called redundant array creation, because you are creating an array that you don't need to use explicitly. This can have a negative impact on the performance and memory usage of your program, especially if you call the varargs method frequently or with many arguments.
To avoid redundant array creation, you can either reuse an existing array, or use a static final array constant. For example, if you want to print the same strings repeatedly, you can store them in an array and pass it to the method:
private static final String[] GREETINGS = "Hello", "World"; ... printStrings(GREETINGS);
This way, you only create one array and use it multiple times, saving memory and improving performance. Alternatively, you can use a static final array constant, which is a compile-time constant expression that represents an array. For example:
private static final String[] GREETINGS = "Hello", "World"; ... printStrings(new String[] "Hello", "World"); // redundant array creation
printStrings(GREETINGS); // no redundant array creation
printStrings(new String[0]); // no redundant array creation
printStrings(); // no redundant array creation
The last three calls do not create redundant arrays, because they use static final array constants. The compiler can optimize these calls and avoid creating unnecessary arrays at runtime.
In summary, redundant array creation for calling varargs methods can be avoided by reusing existing arrays or using static final array constants. This can improve the performance and memory efficiency of your program.
a104e7fe7e