Home > Common Problem > java array assignment method

java array assignment method

小老鼠
Release: 2024-05-09 23:54:16
Original
465 people have browsed it

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 method

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>
Copy after login

2. Use loop

<code class="java">int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
    arr[i] = i + 1;
}</code>
Copy after login

3. Use Arrays.fill() method

<code class="java">int[] arr = new int[5];
Arrays.fill(arr, 5); // 将所有元素填充为 5</code>
Copy after login

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>
Copy after login

5. Use streaming API

<code class="java">int[] arr = IntStream.rangeClosed(1, 5).toArray(); // 将整数流转换为数组</code>
Copy after login

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>
Copy after login

The above is the detailed content of java array assignment method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template