java 在java中的arraylist中打印数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10081829/
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
printing elements of array in arraylist in java
提问by user1322978
I do have this code, and I would like to print out all the array's values of Arraylist. thanks for your help in advanced.
我确实有这个代码,我想打印出 Arraylist 的所有数组值。感谢您在高级方面的帮助。
here is my code:
这是我的代码:
for (int i = 0; i <count; i++) {
System.out.println("list #" + i);
for (int j = 0; j < list[i].size(); j++) {
list[i].get(j);
System.out.println("elements of array in arraylist "+list[i].get(j));
}
}
回答by ring bearer
For printing elements of an array stored in arraylist,you will have to to do the following:
要打印存储在 arraylist 中的数组元素,您必须执行以下操作:
for each element of arraylist
get array from arraylist
for each array element in array
print array element.
You seemed to be iterating array of List type instead.
您似乎正在迭代 List 类型的数组。
Edit your code with further detail on your data structure
使用有关数据结构的更多详细信息编辑您的代码
回答by dash1e
for (Object[] array : list)
for (Object o : array)
System.out.println("item: " + o);
回答by duffymo
See if this can work for you. I think it's simpler:
看看这是否适合你。我认为它更简单:
int numLists = 10; // Or whatever number you need it to be.
ArrayList [] arrayOfLists = new ArrayList[numLists];
// you realize, of course, that you have to create and add those lists to the array.
for (ArrayList list : arrayOfLists) {
System.out.println(list);
}
I'd wonder why you don't prefer a List of Lists:
我想知道为什么你不喜欢列表列表:
List<List<String>> listOfLists = new ArrayList<List<String>>();
// add some lists of Strings
for (List<String> list : listOfLists) {
System.out.println(list);
}
回答by Varsha
Below code works fine for me
下面的代码对我来说很好用
public class Solution
{
public static void main(String[] args)
{
int T,N,i,j,k=0,Element_to_be_added_to_the_array;
Scanner sn=new Scanner(System.in);
T=sn.nextInt();
ArrayList<Integer>[] arr=new ArrayList[T];
for(i=0;i<T;i++)
{
arr[k]=new ArrayList<Integer>();
N=sn.nextInt();
for(j=0;j<N;j++)
{
Element_to_be_added_to_the_array=sn.nextInt();
arr[k].add(Element_to_be_added_to_the_array);
}
k++;
}
//Printing elements of all the arrays contained within an arraylist
for(i=0;i<T;i++)
{
System.out.println("array["+i+"]");
for(j=0;j<arr[i].size();j++)
{
System.out.println(arr[i].get(j));
}
}
}
}