0

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

我正在使用一个列表,其中每一行都是一组:

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 的一维数组?如何解决这个问题?

4

2 回答 2

4

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

于 2012-12-17T23:29:49.000 回答
0

你需要修复你的循环:

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

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

for(int j=0;j<5;j++){    
    tempBridge = getBridges();
    bridges.add(tempBridge);
    System.out.println(bridges.size());
}    


Set<String> getBridges(){
    Set<String> temp = new HashSet<String>();
    for(int k=0;k<8;k++){
        // Add some data to temp
        temp.add("test" + Integer.toString(k));
    }
    return temp;
}
于 2012-12-18T00:04:51.143 回答