Can someone explain to me what the reasoning behind passing by “value” and not by “reference” in Java is?

后端 未结 15 1406
[愿得一人]
[愿得一人] 2020-12-31 17:24

I\'m fairly new to Java (been writing other stuff for many years) and unless I\'m missing something (and I\'m happy to be wrong here) the following is a fatal flaw...

<
15条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 18:08

    Your question as asked doesn't really have to do with passing by value, passing by reference, or the fact that strings are immutable (as others have stated).

    Inside the method, you actually create a local variable (I'll call that one "localFoo") that points to the same reference as your original variable ("originalFoo").

    When you assign "howdy" to localFoo, you don't change where originalFoo is pointing.

    If you did something like:

    String a = "";
    String b = a;
    String b = "howdy"?
    

    Would you expect:

    System.out.print(a)
    

    to print out "howdy" ? It prints out "".

    You can't change what originalFoo points to by changing what localFoo points to. You can modify the object that both point to (if it wasn't immutable). For example,

    List foo = new ArrayList();
    System.out.println(foo.size());//this prints 0
    
    thisDoesntWork(foo);
    System.out.println(foo.size());//this prints 1
    
    public static void thisDoesntWork(List foo){   
        foo.add(new Object);
    }
    

提交回复
热议问题