有六種方法可以用 Java 數組存儲元素:通過逐個元素賦值、使用 Arrays.fill()、使用 collections.ncopies()、使用 stream.of() 和 arrays.stream()、使用 system.arraycopy() 方法以及使用 for 循環。每種方法都可以將元素存滿到數組中,并且具有不同的實現步驟。
如何用 Java 數組存滿元素
直接賦值
最簡單的方法是用賦值語句逐個元素賦值。例如:
int[] numbers = new int[10]; for (int i = 0; i <p><strong>使用 Arrays.fill()</strong></p><p><span>立即學習</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免費學習筆記(深入)</a>”;</p><p>Arrays.fill() 方法可以將數組指定范圍內的元素全部賦值為指定值。例如:</p><pre class="brush:php;toolbar:false">int[] numbers = new int[10]; Arrays.fill(numbers, 10);
登錄后復制
使用 Collections.nCopies()
Collections.nCopies() 方法可以生成一個包含指定元素值的指定長度的列表。然后可以將此列表轉換為數組。例如:
int[] numbers = new int[10]; List<integer> values = Collections.nCopies(10, 10); numbers = values.toArray(new Integer[0]);</integer>
登錄后復制
使用 Stream.of() 和 Arrays.stream()
Stream.of() 方法可以生成一個元素流,而 Arrays.stream() 方法可以將數組轉換為流。可以使用這些流將元素逐個添加到數組中。例如:
int[] numbers = new int[10]; // 通過 Stream.of() IntStream.range(0, 10).forEach(i -> numbers[i] = i); // 通過 Arrays.stream() Arrays.stream(numbers).forEach(i -> i = 10);
登錄后復制
使用 System.arraycopy()
System.arraycopy() 方法可以將數組的一部分復制到另一個數組中。這可以用來將元素從一個數組存滿到另一個數組中。例如:
int[] numbers1 = {1, 2, 3, 4, 5}; int[] numbers2 = new int[10]; System.arraycopy(numbers1, 0, numbers2, 0, numbers1.Length);
登錄后復制