【发布时间】:2021-07-04 12:33:05
【问题描述】:
我想在不使用 for 循环的情况下初始化一个嵌套列表,根列表是: cakeList 将包含另一个,例如(100)。
我的代码:
1. ArrayList<ArrayList<Integer>> cakeList = new ArrayList<>();
2. for (int i=0;i<100;i++) cakeList.add(new ArrayList<>());
我试过了:
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> cakeList = new ArrayList<>(100);
cakeList.forEach(e-> new ArrayList<>());
System.out.println(cakeList.size());
cakeList.get(0);
}
}
但您可能知道,它符合要求,但在第 7 行抛出错误,因为当我尝试使用 cakeList.get(0) 时 cakeList 为空。
IndexOutOfBoundsException:索引:0,大小:0
提前谢谢你!
【问题讨论】:
-
第二种方法使用 lamda 将给出 IndexOutOfBoundsException 因为 cakeList 最初是空的。您在尝试第一种方法时是否遇到任何问题?
-
cakeList.forEach(e-> new ArrayList<>());这个方法是的会抛出异常,因为 cakeList 是空的。 -
@HeribertoHaydar,
cakeList.forEach在cakeList为空时不会抛出IndexOutOfBoundsException,因为这里没有索引。请澄清您的问题。 -
正如 Alex Rudenko 所说,也不例外,你想在不使用 for 循环的情况下初始化你的
cakeList,例如使用Stream吗? -
@AlexRudenko 我重写了代码。你是对的,因为列表是空的,所以抛出异常。不,因为 ```` cakeList.forEach(e-> new ArrayList() ); ```这段代码。 :)
标签: java performance arraylist