创建数组的数组列表

编程入门 行业动态 更新时间:2024-10-23 05:37:08
本文介绍了创建数组的数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试创建字符串数组的数组列表.完成后,我希望数组列表如下所示:

I'm trying to create an array list of string arrays. When I am done, I want the array list to look like this:

[0,0], [0,1], [1,0], [1,1,]

我尝试定义一个数组,然后将其添加到数组列表中.然后重新定义一个数组并再次添加它.但是数组列表似乎只包含最后一个条目.看一看:

I have tried to define an array and then add it to the array list. Then re-define an array and add it again. But the array list only seems to contains the last entry. Take a look:

String[] t2 = new String[2]; 

ArrayList<String[]> list2 = new ArrayList<String[]>();

t2[0]="0";
t2[1]="0";
list2.add(t2);
t2[0]="0";
t2[1]="1";
list2.add(t2);
t2[0]="1";
t2[1]="0";
list2.add(t2);
t2[0]="1";
t2[1]="1";
list2.add(t2);

for (String[] tt : list2) 
{
System.out.print("[");
for (String s : tt)
System.out.print(s+" ");
System.out.print("]");
}

输出为:

[1,1] [1,1] [1,1] [1,1]

知道如何将每个数组添加到我的数组列表中吗?`

Any idea on how to add each array to my array list?`

推荐答案

问题是您正在向 ArrayList 的每个索引添加相同的对象.每次修改它时,都是在修改同一个对象.为了解决这个问题,你必须传递对不同对象的引用.

The problem is that you are adding the same object to each index of your ArrayList. Every time you modify it, you are modifying the same object. To solve the problem, you have to pass references to different objects.

String[] t2 = new String[2]; 

ArrayList<String[]> list2 = new ArrayList<String[]>();

t2[0]="0";
t2[1]="0";
list2.add(t2); 

t2 = new String[2]; // create a new array
t2[0]="0";
t2[1]="1";
list2.add(t2);

t2 = new String[2];
t2[0]="1";
t2[1]="0";
list2.add(t2);

t2 = new String[2];
t2[0]="1";
t2[1]="1";
list2.add(t2);

这篇关于创建数组的数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 10:41:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!