1. Member
Join Date
Nov 2009
Posts
6
Rep Power
0

## Problem with vector

hi,
I want to make a vector of arrays, fill it with arrays and than display
Java 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];

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.
Java 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
Last edited by morghul; 11-04-2009 at 02:57 AM.

2. 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:
Java 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];

System.out.println("**dane*****");
for(int j=0;j<4;j++){
System.out.print(" " +dane[j]);
}
}```
to this:
Java 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];

System.out.println("**dane*****");
for(int j=0;j<4;j++){
System.out.print(" " +dane[j]);
}
}```

3. Member
Join Date
Nov 2009
Posts
6
Rep Power
0
It works:) thx for help

4. 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.