In Java, an anonymous array is an array that is created and used in a single location, and does not have a name. Anonymous arrays are often used to pass a fixed set of values to a method as an argument.
Here is an example of how to use an anonymous array to pass a list of integers to a method:
public void printNumbers(int[] numbers) { for (int number : numbers) { System.out.println(number); } } ... printNumbers(new int[] {1, 2, 3, 4, 5});
In this example, the anonymous array new int[] {1, 2, 3, 4, 5}
is passed as an argument to the printNumbers()
method. The method iterates over the array and prints each element to the console.
Anonymous arrays can be useful when you need to pass a fixed set of values to a method and don't want to create a separate array variable for them. However, they should be used with caution, as they can make the code more difficult to understand if overused.
Anonymous arrays can also be used to create and initialize an array in a single line of code:
int[] numbers = new int[] {1, 2, 3, 4, 5};
In this example, the anonymous array is used to create and initialize the numbers
array in a single line of code.