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

标签 java

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

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

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/

相关文章:

java - 将 ArrayList 转换为 HashMap

java - 绝对值计算不起作用...?

java - 为什么Class.forName ("Test").getClassLoader()?

java - 无法运行命令 `/opt/jdk1.8.0_131/bin/java' : No such file or directory

java - javap 输出中缺少指令编号

java - 让 RestAssured 测试与 Spring Security CSRF for AngularJS 一起使用

java - 将 EditText 和 Spinner 数据插入 SQLite?

java - 如何知道何时调用了 Parse.initialize()?

Java List.addAll 使用集合的流而不是使用集合本身?

java - 如何用Java读取Excel的输入?