Can I initialize an array with all -1 in Java? What is the shortest code for that?
- User
Can I initialize an array with all -1 in Java? What is the shortest code for that?
Assistant
Yes, you can initialize an array with all -1 in Java.
The shortest code for that is:
javaint[] array = new int[SIZE]; // Replace SIZE with your desired array size Arrays.fill(array, -1); // Import java.util.Arrays;Alternatively, you can use a loop or Java 8 streams:
javaint[] array = IntStream.range(0, SIZE).map(i -> -1).toArray(); // Import java.util.stream.IntStream;However, if you want a one-liner without any additional operations, you can create a method:
javapublic static int[] initArray(int size, int value) { int[] array = new int[size]; Arrays.fill(array, value); return array; } // Usage: int[] array = initArray(SIZE, -1);
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.