如何填写列表列表? [英] How to fill a List of Lists?

查看:30
本文介绍了如何填写列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个这样的列表:

I create a list of lists like this:

List<List> tmp = new ArrayList<List>(2);

然后我想插入 10 到第一个子列表如下:

Then I'd like to insert 10 to first sub-list as follows:

tmp.get(0).add(10);

但是,我收到以下错误:

However, I get the following error:

线程main"中的异常java.lang.IndexOutOfBoundsException:索引:0,大小:0在 java.util.ArrayList.rangeCheck(ArrayList.java:653)在 java.util.ArrayList.get(ArrayList.java:429)

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429)

错误的根源是什么,我该如何克服?

What is the source of error and how can I overcome it ?

推荐答案

您已经创建了一个初始容量为 2 的空列表(即列表的内部表示直到您已经向其中添加了 2 个元素,并且正在添加第三个).

You've created an empty list with initial capacity of 2 (i.e. the internal representation of the list won't be resized until you've added 2 elements to it and are adding the third).

然后您尝试从空列表中获取第一个元素.这自然行不通.您需要首先 add() 根据需要添加尽可能多的内部列表(大概是 2 个),然后然后填充这些内部列表.

Then you try to get the first element from the empty list. Naturally this won't work. You need to first add() as many inner lists (presumably 2) as you want, and then fill those inner lists.

这篇关于如何填写列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆