This question already has an answer here:
这个问题在这里已有答案:
- How do I declare and initialize an array in Java? 19 answers
- 如何在Java中声明和初始化数组? 19个答案
I want to know how I can name a variable dynamically.
我想知道如何动态命名变量。
If there are 3 items in a list then it should create 3 different object for each item. Like:
如果列表中有3个项目,则应为每个项目创建3个不同的对象。喜欢:
ArrayList<String> list1;
ArrayList<String> list2;
ArrayList<String> list3;
So it should count up or anything like that.
所以它应该计数或类似的东西。
if there are 4 items in a list it should create 4 variables.
如果列表中有4个项目,则应创建4个变量。
How can I achieve that?
我怎样才能做到这一点?
Edit:
编辑:
I tried this but it says me an error that I can't create a generic array of Info.
我试过这个,但它告诉我一个错误,我不能创建一个通用的Info数组。
ArrayList<Info> listForLg[] = new ArrayList<Info>[];
for (int i = 0; i < sizeOfKfzList; i++) {
listForLg[i] = new ArrayList<Info>();
listForLg[i].add(logInfo);
}
Can you help me?
你可以帮我吗?
3 个解决方案
#1
2
Use arrays
使用数组
ArrayList<String> list[] = new ArrayList<String>[3]; //or 4 or n
Then access them like
然后像访问它们一样
list[0] = "123";
#2
2
Use Array for this...
使用数组...
ArrayList<String> yourlist[] = new ArrayList<String>([your size here])
Based on index use your variable..
基于索引使用你的变量..
yourlist[0] yourlist[1]....and so on
Hope this could help
希望这可以帮助
#3
1
Create list or arraylist
创建列表或arraylist
ArrayList<ArrayList<String>> group = new ArrayList<ArrayList<String>>(4);
or
要么
List<List<String>> group1 = new ArrayList<List<String>>(4);
Edit:
编辑:
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
To add (u can add items dynamically by loop)
添加(你可以通过循环动态添加项目)
group.add(list1);
and to get
得到
list2= group.get(0);
#1
2
Use arrays
使用数组
ArrayList<String> list[] = new ArrayList<String>[3]; //or 4 or n
Then access them like
然后像访问它们一样
list[0] = "123";
#2
2
Use Array for this...
使用数组...
ArrayList<String> yourlist[] = new ArrayList<String>([your size here])
Based on index use your variable..
基于索引使用你的变量..
yourlist[0] yourlist[1]....and so on
Hope this could help
希望这可以帮助
#3
1
Create list or arraylist
创建列表或arraylist
ArrayList<ArrayList<String>> group = new ArrayList<ArrayList<String>>(4);
or
要么
List<List<String>> group1 = new ArrayList<List<String>>(4);
Edit:
编辑:
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
To add (u can add items dynamically by loop)
添加(你可以通过循环动态添加项目)
group.add(list1);
and to get
得到
list2= group.get(0);