有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将LinkedList的ArrayList清空回数组

我正在尝试将LinkedList的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();
   }
}

我会在假设while不为空的情况下进行操作,以解释这一点。我很好奇为什么它不能成功地复制内容


共 (2) 个答案

  1. # 1 楼答案

    这样就行了。本例使用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]
    
    
  2. # 2 楼答案

    代码中有几个问题

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