[英]How to add and retrieve the values in Arraylist of ArrayList
我知道如何创建 ArrayList
的ArrayList
,但是知道如何添加新的ArrayList
并为该特定ArrayList
添加值以及如何从该列表中检索数据。
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<ArrayList<Integer>>();
You can try this 你可以试试这个
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
ArrayList<Integer> list1=new ArrayList<>();
ArrayList<Integer> list2=new ArrayList<>();
list1.add(1); // add to list
list1.add(2);
list2.add(3);
list2.add(4);
arrayList.add(list1); // add to list of list
arrayList.add(list2);
for(ArrayList<Integer> i:arrayList){ // iterate -list by list
for(Integer integer:i){ //iterate element by element in a list
}
}
You can get element directly 您可以直接获取元素
arrayList.get(0).get(0); // 0th list 0th value
adding value to 0th list 为第0个列表添加值
arrayList.get(0).add(1); // 1 will add to 0th index list-list1
how to add new ArrayLists and ADD value to that particular ArrayList and how to RETRIEVE the data form that list.
如何向该特定ArrayList添加新的ArrayLists和ADD值,以及如何从该列表中检索数据。
ArrayList<ArrayList<Integer>> arrayList=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> newAL= new ArrayList<Integer>();
arrayList.add(newAL);
newAL.add(1);
newAL.add(2);
newAL.clear();
System.out.println(arrayList.get(0));
//Changes persist in your arraylist
So after adding ArrayList you can manipulate newAL
as ArrayList
stores reference you don't need to fetch and set element from main arrayList
. 因此,在添加ArrayList之后,您可以操纵
newAL
因为ArrayList
存储引用时,您不需要从主arrayList
获取和设置元素。
To retrive data you can Iterate
(Use ForEach Loop ) over arrayList
or you can do following 要检索数据,可以在
arrayList
进行Iterate
(使用ForEach循环 ),也可以执行以下操作
Integer List0Item1=arrayList.get(0).get(1);//Get first element of list at 0
arrayList.get(0).set(0, 10);//set 0th element of list at 0 as 10
ArrayList<Integer> list10=arrayList.get(10);//get arraylist at position 10
It is a list of list where every object of the parent list is in turn a sublist.The code is something like below: 它是一个列表列表,其中父列表的每个对象又是一个子列表。代码如下:
List<List<String>> mainList = new ArrayList<List<String>>();
List<String> sublist1 = new ArrayList<String>();
sublist1.add("State");
sublist1.add("Country");
sublist1.add("City");
mainList .add(sublist1);
List<String> sublist2 = new ArrayList<String>();
sublist2.add("Sleep");
sublist2.add("Suspend");
sublist2.add("Wait");
mainList .add(sublist2);
for(List<String> obj:mainList){ // iterate
for(String value:obj){
System.out.println(value);
}
}
}
}
Hope this will help to clear your doubt.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.