0

I tired the following Java code and the result was "null". I thought two n are same pointer pointing to different memory (in main function and in test function). If I initiate n as null in main function, assign it in test function and want to use it outside test function (without return n itself). How can I do it?

public class ttt {
    static class LinkNode {
        int val;

        public LinkNode(int p) {
            val = p;
        }

    }

    public static void test(Set<LinkNode> n) {
        n = new HashSet<>();
        LinkNode a = new LinkNode(1);
        n.add(a);
    }

    public static void main(String[] args) {
        Set<LinkNode> n = null;
        test(n);
        System.out.println(n);
    }

}
  • possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Vitruvie Mar 24 '15 at 03:53
  • yes, duplicated. it's a pass value/reference issue here. – G Bisconcini Mar 24 '15 at 03:58
  • I notice is the first line in test function causing the trouble, but what if I dont know if n is null or not, and I want to check it inside of test function. if it is null i want to init it inside test function. what can I do? – user3483236 Mar 24 '15 at 04:01
  • @user3483236 You cannot do anything in `test` that can change the value of `n` in `main`. The normal way to write code where methods can access the same variable like this, is to make the variable a `private` instance field in a class, and make the methods non-`static` methods in the class. – ajb Mar 24 '15 at 04:08

1 Answers1

0

When you did

n = new HashSet<>();

you overwrote the value of n passed into test(...) but that doesn't reset the value of n in main(...)

This means that you added a to the new LinkNode you created within test(...) but since n in main(...) refers to the old null LinkNode the assignment and addition are lost to the garbage collector after exiting test(...)

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138