When I try to add List to List in Java

I faced a problem when I try to add List to List< List > in java, and it did consume some my time. It is a common problem and I even can remember I got stuck on debugging because of this "feature" at least twice.
To let me remember this problem and avoid making it again, I decided to take a note on that.
First let us take a look on my code:

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> tmp = new ArrayList<>();
    ....
    res.add(tmp);

In this case, actually I added the reference of tmp to the res, the current tmp is "non-static". It means the result I stored into res will change when I change the content of tmp. To fix this , I should rather use code as below:

res.add(new ArrayList<Integer>(tmp));

Leave a Reply