Make 'makenull' a member function that accepts no arguements instead of
static with arguement and it will work. Can you see why? The reference s
that the body of makenull sees is a copy of the reference you created in
your main method. If you are familiar with C you might recall that for a
method to set a pointer to null it must receive a pointer to the pointer.
void makenull(**ptr) {
*ptr = null;
}
void main(int argc, char** argv) {
void *vPtr = malloc(16);
vPtr = makenull(&vPtr); // pass in the address of the pointer,
// not the pointer itself.
}
The only way I can think of to accomplish the same kind of behavior in
java is to wrap the reference inside of another reference.
public class Foo {
private String s;
public static void makeSnull(Foo outterRef) {
outterRef.s = null;
}
public static void main(String[] args) {
Foo foo = new Foo();
Foo.makeSnull(foo);
}
}
roy wrote:
The following is a simple example I wrote.
I want function makenull() to set the arraylist null.
However, in this example, after coming back from makenull() function,
s is still not null.
I got confused. Anyone can give me some help?
public class test {
public static void makenull(java.util.ArrayList s){
s = null;
}
public static void main(String[] args) {
java.util.ArrayList s = new java.util.ArrayList();
test.makenull(s);
// after test.makenull function, s is NOT null
}
}
Thanks