java 如何在二维 ArrayList 上调用 .get()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15324925/
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-10-31 19:14:56  来源:igfitidea点击:

How do I call .get() on a 2d ArrayList

java

提问by papercuts

I have a 2d ArrayList

我有一个 2d ArrayList

ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

I want to get the item at say (0,0).

我想在 say (0,0) 处获取该项目。

I'm looking for something like:

我正在寻找类似的东西:

list.get(0,0)

Thanks!

谢谢!

回答by Hyman

You must use

你必须使用

list.get(0).get(0)

since you are not using a real 2-dimensional Listbut a Listof Lists.

因为你没有使用真正的2维List而是ListLists

回答by Bhesh Gurung

As follows

如下

String value = list.get(0).get(0);

回答by Ted Hopp

Java doesn't have 2d lists (or arrays, for that matter). Use something like this:

Java 没有二维列表(或数组,就此而言)。使用这样的东西:

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]

回答by Aravinth

This is a program to traverse the 2D-ArrayList. In this program instead of LineXyour can get item in the list (i , j ) :-)

这是一个遍历 2D-ArrayList 的程序。在这个程序而不是LineX 中,您可以获得列表中的项目 (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

回答by Jeevan Patil

It being List of List, you try :

它是列表列表,您尝试:

String val = list.get(0).get(0);