0

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); , that variable also automatically add to g_nodes before the running g_nodes.add(g_tempNodes); .

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]]
Sandar Min Aye
  • 499
  • 6
  • 15
  • 28
  • possible duplicate of [Why does my ArrayList contain N copies of the last item added to the list?](http://stackoverflow.com/questions/19843506/why-does-my-arraylist-contain-n-copies-of-the-last-item-added-to-the-list) – Duncan Jones Jan 06 '14 at 12:48

1 Answers1

1

Since you're using the same g_tempNodes always, the values are getting overwritten. Declare a new g_tempNodes in the loop always

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
    ...
}
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • I use g_tempNodes to know the old variable so that I think it should not add in while loop. I'm still wonder that g_nodes and g_tempNodes is not the same variable and how to add to g_nodes (before arrive that sentence) while running in add to g_tempNodes. – Sandar Min Aye Nov 12 '13 at 09:39
  • 1
    they are not the same. But the `g_tempNodes` keeps changing in every iteration and that is why you need to create a `g_tempNodes` instead of re-using the same. A change in the `g_tempNodes` in the `g_nodes`, as only the reference of the `g_tempNodes` is copied in the list and any change to it, will be reflected back in the `g_nodes_ list. – Rahul Nov 12 '13 at 09:42
  • I care your comment and I got the experience from your comment. I didn't downvoter your answer. – Sandar Min Aye Nov 13 '13 at 01:55