我遇到了这个问题,但没有找到任何确切的解释。我在 Debug模式下运行程序,我看到当变量添加到 g_temNodes 数组列表时: g_tempNodes.add(p_dept_cd); ,该变量也会在运行 g_nodes 之前自动添加到 g_nodes 。添加(g_tempNodes); .
请给我一些解决的方法。提前致谢。
我的代码如下。
ArrayList<ArrayList<String>> g_nodes = new ArrayList<ArrayList<String>>();
ArrayList<String> g_tempNodes = new ArrayList<String>();
...
...
private String GetDeptCd(String x_dept_cd, int x_flag) {
...
...
while (p_sql.next()) {
String p_dept_cd = p_sql.getString("dept_cd");
if(x_flag == 0){
g_tempNodes.removeAll(g_tempNodes);
}
g_tempNodes.add(p_dept_cd);
System.out.println("g_tempNodes = "+g_tempNodes);
g_nodes.add(g_tempNodes);
System.out.println("g_nodes = "+g_nodes);
GetDeptCd(p_dept_cd, 1);
g_tempNodes.remove(g_tempNodes.size()-1);
}
return null;
}
这是控制台中的输出。
g_tempNodes = [100]
g_nodes = [[100]]
g_tempNodes = [100, 999]
g_nodes = [[100, 999], [100, 999]]
g_tempNodes = [100, 101]
g_nodes = [[100, 101], [100, 101], [100, 101]]
最佳答案
由于您始终使用相同的 g_tempNodes
,因此这些值会被覆盖。始终在循环中声明一个新的 g_tempNodes
ArrayList<ArrayList<String>> g_nodes = new ArrayList<ArrayList<String>>();
// ArrayList<String> g_tempNodes = new ArrayList<String>(); // not needed here
...
while (p_sql.next()) {
ArrayList<String> g_tempNodes = new ArrayList<String>(); // new list created always
...
}
关于java - 将值添加到其他数组列表后覆盖数组列表中的旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19924902/