Reputation: 2676
I am trying to add an arraylist in an arraylist in a for loop. When I clear the data in second one, it clears in second arraylist data in first arraylist. Let me explain with code:
ArrayList arrTemp = new ArrayList();
ArrayList arrTemp2 = new ArrayList();
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
//Here I add some strings in arrTemp
}
arrTemp2.add(arrTemp); //I will add arrTemp 10 times with different data in it to arrTemp2
arrTemp.clear(); //Everytime I want to clear the arrTemp
//But when I clear it, it also clears already added arrTemp in arrTemp2
}
I want it to have 10 different arrTemp in arrTemp2
Upvotes: 1
Views: 102
Reputation: 11
I'm not positive, but it seems to me that your addTemp2.add(arrTemp) is not working as intended. Have you tried debugging and checking whether arrTemp2 is actually being populated with something after that line fires? Looking at the documentation (below) for ArrayLists, I think you might want addAll instead. Alternately, you could iterate over arrTemp and add each element individually to arrTemp2 before you clear arrTemp.
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Upvotes: 0
Reputation: 36304
arrTemp2.add(arrTemp);// will add arrTemp object's reference to your arrTemp2.
So, once you clear arrTemp, you actually will clear() the space being pointed by arrTemp.
use Generics with addAll(), like this:
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
ArrayList<Integer> al2 = new ArrayList<Integer>();
al2.add(3);
al.addAll(al2);
al2.clear();
System.out.println(al);
}
O/P : [1, 2, 3]
Your case :
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(1);
al.add(2);
ArrayList al2 = new ArrayList();
al2.add(3);
al.add(al2);
al2.clear();
System.out.println(al);
}
O/P : [1, 2, []] // 3rd item is considered as an Object
Upvotes: 1
Reputation: 11579
for(int i = 0; i < 10; i++)
{
arrTemp = new ArrayList();
for(int j = 0; j < 10; j++)
.....
You will have different array for each i
.
Upvotes: 2