[英]Overwrite to old value in arraylist after added the values to other arraylist
I'm facing the problem and I did not find for any exact explanation for it. 我正在面对问题,但没有找到确切的解释。 I am running the program in debug mode, I see that when the variable add to g_temNodes arraylist: g_tempNodes.add(p_dept_cd); 我在调试模式下运行程序,我看到当变量添加到g_temNodes arraylist中时: g_tempNodes.add(p_dept_cd); , that variable also automatically add to g_nodes before the running g_nodes.add(g_tempNodes); ,该变量还会在运行g_nodes.add(g_tempNodes);之前自动添加到g_nodes ; . 。
Pls give me some ways to solve it. 请给我一些解决方法。 Thanks in advance. 提前致谢。
my code is as the followings. 我的代码如下。
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;
}
This is the output in console. 这是控制台中的输出。
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]]
Since you're using the same g_tempNodes
always, the values are getting overwritten. 由于您始终使用相同的g_tempNodes
,因此这些值将被覆盖。 Declare a new g_tempNodes
in the loop always 总是在循环中声明一个新的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
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.