java 如何打印 ArrayLists 的 ArrayList,以便每个内部列表都打印在一行上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10176271/
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
How to print an ArrayList of ArrayLists so that each inner list is printed on one row?
提问by Anurag Ramdasan
I have an ArrayList of ArrayLists - something like ArrayList<ArrayList<Node>>
.
Since I get this as a return value from a function, after every call a different size is called. I am wondering how to display its elements is such a way that the inner ArrayList constitutes one row and so for every row.
我有一个 ArrayLists 的 ArrayList - 类似于ArrayList<ArrayList<Node>>
. 由于我将其作为函数的返回值获取,因此每次调用后都会调用不同的大小。我想知道如何以内部 ArrayList 构成一行的方式显示其元素,因此对于每一行。
What would be my required parameter(s) for the for loop? Thanks in advance.
for 循环所需的参数是什么?提前致谢。
回答by giorashc
for (List<Node> l1 : arrayLists) {
for (Node n : l1) {
System.out.print(n + " ");
}
System.out.println();
}
回答by Luiggi Mendoza
Here is a basic sample:
这是一个基本示例:
public static void main(String[] args) {
List<List<String>> ls;
//initialize ls and set values in it...
//after set some values, let's print it
for(List<String> innerLs : ls) {
String[] arr = innerLs.toArray();
System.out.println(Arrays.deepToString(arr));
}
}
It should be the same logic for List<List<T>>
.
应该是相同的逻辑List<List<T>>
。
回答by Chandra Sekhar
invoke iterator()
which will return an Iterator<ArrayList<Node>>
, and loop on that.
invokeiterator()
将返回一个Iterator<ArrayList<Node>>
, 并在其上循环。
Inside the loop invoke iterator()
again, on each iterated elements, which will return a Iterator<Node>
; use an inner loop and use next()
on it to display.
在循环内部iterator()
再次调用,在每个迭代元素上,这将返回一个Iterator<Node>
; 使用内循环并使用next()
它来显示。
For the loops use either a 'foreach' loop (for(Node n : iterator)
) or a while loop (while(iterator.hasNext())
).
对于循环,使用“foreach”循环 ( for(Node n : iterator)
) 或 while 循环 ( while(iterator.hasNext())
)。