如何在java中创建一个ArrayLists数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22747528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:40:17 来源:igfitidea点击:
How to create an array of ArrayLists in java?
提问by airbourne
I am creating an array but cannot add values to it.
我正在创建一个数组,但无法为其添加值。
ArrayList<SMS>[] lists = (ArrayList<SMS>[])new ArrayList[count];
for(int i=0;i<temp.size();i++)
{
String number="",id="";
number = temp.get(i).addr;
id = temp.get(i).thread_id;
lists[i].add(temp.get(i)); // Problem here
}
I am unable to add value to it
我无法为其增值
采纳答案by Thomas
You're creating an array of null
references, so you need to initialize each of them to a new ArrayList<SMS>()
:
您正在创建一个null
引用数组,因此您需要将每个引用初始化为new ArrayList<SMS>()
:
for (int i = 0; i < count; i++) {
lists[i] = new ArrayList<SMS>();
}
回答by Thalaivar
int size = 9;
ArrayList<SMS>[] lists = new ArrayList[size];
for( int i = 0; i < size; i++) {
lists[i] = new ArrayList<SMS>();
}