2

I made this code

private static List<String> rebuildURLWithComplexValues(String url) {

List<String> tokens = null;

if(url != null && url.length() > 0) {
    if(url.contains("flowVars")) {              
        String[] firstSplit = url.split("\\[");
        for (int i = 0; i < firstSplit.length; i++) {
            if(firstSplit[i].contains("'")) {
                StringTokenizer st = new StringTokenizer(firstSplit[i], "\'");
                tokens = new ArrayList<String>();
                String token = st.nextToken();
                System.out.println(token);
                tokens.add(token);
            }
        }

        return tokens;
    }
}
return null;
}

The Sysout shows each token correctly, but when i then iterate the arrayList or check its size, says 1 (when should be 2) and shows only the latest token added.

Why is this happening???

Thanks.

4

1 回答 1

7

ArrayList您正在for 循环的每次迭代中创建一个新的。

移动以下语句:

tokens = new ArrayList<String>();

在 for 循环之外。或者只是tokens在声明的地方初始化 ,而不是将其初始化为null.

于 2013-07-18T20:33:03.413 回答