将LinkedList的ArrayList清空回数组



我正试图将LinkedLists的ArrayList的元素移回数组中。我发现了一个元素未找到异常。

ArrayList<LinkedList<Integer>> stacks = new ArrayList<LinkedList<Integer>>(3);
int[] arr = new arr[5];
stacks.get(0).add(22);
stacks.get(0).add(1);
stacks.get(0).add(7);
stacks.get(1).add(111);
stacks.get(2).add(123);
for (int i = 0; i < arr.length; i++)
{
while (!stacks.isEmpty())
{
arr[i++] = stacks.get(i).remove();
}
}

我会在假设时间不是空的情况下操作,这将解释这一点。我很好奇为什么它不会成功地复制内容?

您的代码中存在几个问题。

int[] arr = new int[5];   // not new arr[]

您没有将LinkedList添加到ArrayList。您需要先添加LinkedList,然后再向stacks添加项目。

你的循环完全错了,我已经重写了。

ArrayList<LinkedList<Integer>> stacks = new ArrayList<>(3);
int[] arr = new int[5];
stacks.add(new LinkedList<>());
stacks.add(new LinkedList<>());
stacks.add(new LinkedList<>());
stacks.get(0).add(22);
stacks.get(0).add(1);
stacks.get(0).add(7);
stacks.get(1).add(111);
stacks.get(2).add(123);
int count = 0;
for (LinkedList<Integer> stack : stacks) {
for (Integer integer : stack) {
arr[count++] = integer;
}
}
System.out.println(Arrays.toString(arr));

这样就可以了。这个例子使用ArrayLists,但它也可以与LinkedLists或任何实现List接口的东西一起使用。

创建列表列表。

ArrayList<List<Integer>> stacks =
new ArrayList<>(List.of(List.of(22, 1, 7),
List.of(111, 112), List.of(44, 123, 99)));

并转换为int array

int[] ints = stacks
.stream()                   // convert to a stream of lists
.flatMap(List::stream)      // combine all lists to one list of Integers
.mapToInt(Integer::intValue)// convert Integers to ints
.toArray();                 // and output to an array.
System.out.println(Arrays.toString(ints));

打印

[22, 1, 7, 111, 112, 44, 123, 99]

最新更新