In Java, the 6 methods of assigning values to arrays include: direct initialization using loops using the Arrays.fill() method copying from another array using the stream API using third-party tool classes (such as Apache Commons Lang)
Java array assignment methods
In Java, there are many ways to assign values to arrays:
1. Direct initialization
<code class="java">int[] arr = {1, 2, 3, 4, 5};</code>
2. Use loop
<code class="java">int[] arr = new int[5]; for (int i = 0; i < 5; i++) { arr[i] = i + 1; }</code>
3. Use Arrays.fill() method
<code class="java">int[] arr = new int[5]; Arrays.fill(arr, 5); // 将所有元素填充为 5</code>
4. Copy from another array
<code class="java">int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = new int[5]; System.arraycopy(arr1, 0, arr2, 0, 5); // 将 arr1 的元素复制到 arr2 中</code>
5. Use streaming API
<code class="java">int[] arr = IntStream.rangeClosed(1, 5).toArray(); // 将整数流转换为数组</code>
6 . Using tool classes
You can use third-party tool libraries (such as Apache Commons Lang) to provide additional array assignment utility methods:
<code class="java">int[] arr = new int[5]; ArrayUtils.add(arr, 1, 2, 3, 4, 5); // 使用 ArrayUtils.add() 逐个添加元素 ArrayUtils.reverse(arr); // 使用 ArrayUtils.reverse() 反转数组</code>
The above is the detailed content of java array assignment method. For more information, please follow other related articles on the PHP Chinese website!