【问题标题】:Emptying an ArrayList of LinkedList back into an Array将 LinkedList 的 ArrayList 清空回 Array
【发布时间】:2020-04-25 00:05:37
【问题描述】:

我正在尝试将 LinkedLists 的 ArrayList 的元素移回 Array。我遇到了一个未找到元素的异常。

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();
   }
}

我会在 while 不为空的假设下进行操作,这可以解释这一点。我很好奇为什么它不会成功将内容复制过来?

【问题讨论】:

  • 空入数组是什么意思?
  • 将它们输入到数组中。所以把stacks.get(0)和stacks.get(1)和stacks.get(2)的元素输入到数组arr中。

标签: java arraylist linked-list


【解决方案1】:

您的代码中有几个问题。

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

您没有将LinkedList 添加到ArrayList。您需要先添加LinkedLists,然后将项目添加到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));

【讨论】:

    【解决方案2】:

    这样就可以了。此示例使用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]
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-07
      • 2011-08-16
      • 2014-06-08
      • 2013-12-07
      • 2014-11-13
      • 2017-10-24
      • 1970-01-01
      • 2017-09-24
      相关资源
      最近更新 更多