Thursday, October 19, 2006

Java Reference

Java passes parameters by reference which brings convinience as well as strange errors. For example:


import java.util.*;

public class Test {
public static void main(String[] args) {
Vector v = new Vector();
int [] a = new int[5];
for(int i=0;i<10;i++) {
for(int j=0;j<5;j++) a[j] = i*j;
v.add(new Obj(a)); // this won't work!
}
for(Iterator it=v.iterator();it.hasNext();) {
it.next().dump();
}
}
}

class Obj {
int [] a;
Obj(int [] a) {
this.a = a;
}
void dump() {
for(int i=0;i System.out.println();
}
}


Well, the line

v.add(new Obj(a));

won't work as expected. Instead all arrays 'a' in 'Obj' are the same.

Change it to

v.add(new Obj(a.clone()));

so that every time a new array is passed.

No comments:

Post a Comment

Please post your comment here. ;)