簡體   English   中英

Arraylist 到數組復制 Java

[英]Arraylist to array copy Java

 ArrayList<ArrayList<Integer>> L1=new ArrayList<>();
 ArrayList<Integer> L2 = new ArrayList<>();
 ArrayList<Integer> L3 = new ArrayList<>();
 ArrayList<Integer> L4 = new ArrayList<>();
 L2.add(5); L3.add(6); L4.add(9);
 L2.add(2); L3.add(1); L4.add(3);
 L2.add(1); L3.add(1); L4.add(2);
 L1.add(L2); L1.add(L3); L1.add(L4);
 L1.remove(L1.size() - 1);

現在我想將從 L1 中刪除的元素保存在一個數組中。 由於此列表包含三個元素,我想創建一個數組,如int ar[] = new int[3]; 並將這個刪除的值保存到這個數組中。

如果您對Integer[]數組沒問題,那么只需使用toArray方法:

ArrayList<Integer> removed = L1.remove(L1.size() - 1);
Integer[] integers = removed.toArray(new Integer[removed.size()]);

如果你想要int[]數組,你可以使用流:

int[] ints = L1.remove(L1.size() - 1).stream().mapToInt(i -> i).toArray();

.mapToInt(i -> i)用於將Integer數值拆箱為int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM