# Problem with vector

• 11-04-2009, 02:26 AM
morghul
Problem with vector
hi,
I want to make a vector of arrays, fill it with arrays and than display
Code:

```Vector<int[]> output= new Vector<int[]>(); for (int k=1;k<h;k+=2){         dane[0]=ar_hor[k-1];         dane[1]=ar_hor[k];         dane[2]=ar_ver[k];         dane[3]=ar_ver_b[k];         output.add(dane);                                         System.out.println("**dane*****");         for(int j=0;j<4;j++){                 System.out.print(" " +dane[j]);         } } System.out.println("--wektor----");                 for (int i=0; i<output.size();i++){         dane=output.get(i);         for(int j=0;j<4;j++){                         System.out.print(" " +dane[j]);                                         } System.out.println(); }```
what do I get? eg.
Code:

```**dane*****  6 30 11 66 **dane*****  36 71 13 66 **dane*****  79 99 33 36 **dane*****  107 128 12 66 **dane*****  133 152 10 66 **dane*****  162 202 7 62 --wektor----  162 202 7 62  162 202 7 62  162 202 7 62  162 202 7 62  162 202 7 62  162 202 7 62```
can anyone expalin me why vestor is filled only with the last array? what should I change to get different array as each element of vector?
thx
• 11-04-2009, 03:16 AM
Fubarable
You never change the dane itself but rather overwrite it each time you change the contents of the array. To fix this, create a new array with each for loop iteration.

Change this:
Code:

```for (int k=1;k<h;k+=2){         dane[0]=ar_hor[k-1];         dane[1]=ar_hor[k];         dane[2]=ar_ver[k];         dane[3]=ar_ver_b[k];         output.add(dane);                                         System.out.println("**dane*****");         for(int j=0;j<4;j++){                 System.out.print(" " +dane[j]);         } }```
to this:
Code:

```for (int k=1;k<h;k+=2){         dane = new int[4]; // if dane is an int array!         dane[0]=ar_hor[k-1];         dane[1]=ar_hor[k];         dane[2]=ar_ver[k];         dane[3]=ar_ver_b[k];         output.add(dane);                                         System.out.println("**dane*****");         for(int j=0;j<4;j++){                 System.out.print(" " +dane[j]);         } }```
• 11-04-2009, 03:22 AM
morghul
It works:) thx for help
• 11-04-2009, 03:24 AM
Fubarable
You're welcome. Perhaps though I should have explained it better. What you were doing was placing a reference to the one single array in each item of Vector. Thus if an item in the array changes, all the arrays seem to change (because they're all the same object). By creating a new array with each iteration of the for loop, you place a new and different array in each item of the Vector.