如何设置嵌套列表的初始容量?

我试图将嵌套的初始容量设置为某个值(例如10),但是当我尝试访问内部列表以添加一些元素时,它给了我。请建议一些好的解决方案!!!ArrayListArrayOutOfBoundException


下面是代码片段


public static void main(String[] args) 

{

    ArrayList<ArrayList<Integer>> bucket = new ArrayList<ArrayList<Integer>>();


    System.out.println(bucket.get(5).add(5));       


    System.out.println(bucket);

}


偶然的你
浏览 103回答 3
3回答

慕村9548890

从 Java 8 开始,您可以使用 生成空列表列表。Stream.generateimport java.util.*;import java.util.stream.*;public class ListOfLists {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; List<List<Integer>> bucket = listOfList(10);&nbsp; &nbsp; &nbsp; &nbsp; bucket.get(5).add(5);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(bucket);&nbsp; &nbsp; }&nbsp; &nbsp; public static <T> List<List<T>> listOfList(int size) {&nbsp; &nbsp; &nbsp; &nbsp; return Stream.generate(ArrayList<T>::new).limit(size).collect(Collectors.toList());&nbsp; &nbsp; }}输出[[], [], [], [], [], [5], [], [], [], []]

婷婷同学_

System.out.println(bucket.get(5).add(5));您需要了解这行代码,您正在尝试从数组列表“存储桶”中访问第5个元素,但是您是否在存储桶中添加了任何元素(在这种情况下,该元素是另一个数组列表)ArrayList除非您添加元素,否则无法访问它们,因为它们不存在,因此您会在尝试访问第5个元素时看到ArrayOutOfBoundExceptionbucket.get(5)你可能想通过ArrayList的javadoc&nbsp;https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

波斯汪

法典:&nbsp;public class Example {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; ArrayList<ArrayList<Integer>> bucket = new ArrayList<ArrayList<Integer>>();&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //initial capacity of the nested arraylist to 5.&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(bucket.add(new ArrayList<>(5)));&nbsp; &nbsp; &nbsp; &nbsp; ArrayList<Integer> element = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; element.add(5);&nbsp; &nbsp; &nbsp; &nbsp; bucket.add(0, element);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(bucket);&nbsp; &nbsp; }}输出:true[[5], []]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java