gpt4 book ai didi

java - Java 中的二维列表/集合

转载 作者:行者123 更新时间:2023-12-01 18:55:59 24 4
gpt4 key购买 nike

我正在寻找的是一个二维字符串数组。同一行中的字符串应该是唯一的,但允许行重复。

我使用的是一个列表,其中每一行都是一个集合:

List<Set<String>> bridges = new ArrayList<Set<String>>();

我有一个返回一组字符串的方法:

Set<String> getBridges(){
Set<String> temp = new HashSet<String>();
// Add some data to temp
temp.add("test1");
temp.add("test2");
temp.add("test3");
return temp;
}

现在在 main 方法中,我将调用 getBridges() 来填充我拥有的列表:

List<Set<String>> bridges = new ArrayList<Set<String>>();

Set<String> tempBridge = new HashSet<String>();

for(int j=0;j<5;j++){
for(int k=0;k<8;k++){
// I call the method and store the set in a temporary storage
tempBridge = getBridges();
// I add the the set to the list of sets
bridges.add(tempBridge);
// I expect to have the list contains only 5 rows, each row with the size of the set returned from the method
System.out.println(bridges.size());
}
}

为什么我得到的列表是大小为 5*8 的一维数组?如何解决这个问题?

最佳答案

您的 for 循环看起来组织不正确。您应该每行只向bridges 添加一次,而现在您每次都通过内部 for 循环添加它,该循环运行 5* 8次。

关于java - Java 中的二维列表/集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13924001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com