I have a 2d ArrayList
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
I want to get the item at say (0,0).
I'm looking for something like:
list.get(0,0)
Thanks!
You must use
list.get(0).get(0)
since you are not using a real 2-dimensional List
but a List
of Lists
.
如下
String value = list.get(0).get(0);
Java doesn't have 2d lists (or arrays, for that matter). Use something like this:
list.get(0).get(0)
Note that arrays have a similar issue. You do not do this:
array[0,0] // WRONG! This isn't Fortran!
Instead you do this:
array[0][0]
它是列表列表,您可以尝试:
String val = list.get(0).get(0);
This is a program to traverse the 2D-ArrayList. In this program instead of your can get item in the list (i , j ) (i,j) 获得项目而不是
PROGRAM:
Scanner scan = new Scanner(System.in);
int no_of_rows = scan.nextInt(); //Number of rows
int no_of_columns = scan.nextInt(); //Number of columns
ArrayList<ArrayList<String>> list = new ArrayList<>();
for (int i = 0; i < no_of_rows; i++) {
list.add(new ArrayList<>()); //For every instance of row create an Arraylist
for (int j = 0; j < no_of_columns; j++) {
list.get(i).add(scan.next()); //Specify values for each indices
}
}
//ArrayList Travesal
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.get(i).size(); j++) {
System.out.print(list.get(i).get(j)+" "); //LineX
}
System.out.println();
}
OUTPUT:
2 3
1 2 3 4 5 6
1 2 3
4 5 6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.