Why is an ArrayList parameter modified, but not a String parameter?

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”? 78 answers

  • In the case of Arraylist string objects the added elements are getting retrived. In case of String the method call has no effect on the String being passed.

    It happens cause Java is Pass-by-Value and String s are immutable

    When you call

    markAsNull(ArrayList<String> str)
    

    The a new reference by name str is created for the same ArrayList pointed by al . When you add an element on str it gets added to same object. Later you put str to null but the object has the new values added and is pointed by a1 .

    When you call

    markStringAsNull(String str)
    {
        str = str + "Append me";
        // ...
    }
    

    The line str = str + "Append me"; creates a new String object by appending the given string and assignes it to str . but again it is just reference to actual string which now pointing to newly created string. (due to immutablity) and the original string is not changed.


    The markXAsNull methods are setting the local references to be null . This has no effect on the actual value stored at that location. The main method still has its own references to the values, and can call println using those.

    Also, when doing the string concatenation, toString() is being called on the Object, and that is why the ArrayList is outputted as a list of its values in brackets.


    In Java, you may create one object, and referenced by multiple pointers. Calling a mutator method on any pointer will effectively modify the sole object, thus updating all other references.

    But if you call variable assignment statements on a reference, only that pointer will be changed, since it doesn't do any object side work (this is the best I could explain...).

    Passing an object to a parameter will effectively copy the reference, resulting in a single object, with two pointers - one global, and the other local.

    One more point, since String is immutable, you'll actually get a new object, that is distinct from the original (from the fact that you have to say a = a + "a" ), that's why it won't modify the original string.

    链接地址: http://www.djcxy.com/p/3506.html

    上一篇: Java是否通过引用传递?

    下一篇: 为什么修改ArrayList参数,但不是String参数?