Java: How to pass byte[] by reference?

前端 未结 3 409
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 06:43

You can do it in .NET by using the keyword \"ref\". Is there any way to do so in Java?

3条回答
  •  佛祖请我去吃肉
    2020-11-30 07:25

    Actually, in Java, the references are passed-by-value.

    In this case, the reference is a byte[] object. Any changes that affect the object itself will be seen from the caller method.

    However, if you try to replace the reference, for example using new byte[length], you are only replacing the reference that you obtained by pass-by-value, so you are not changing the reference in the caller method.

    Here's an interesting read about this issue: Java is Pass-by-Value Dammit!


    Here's an concrete example:

    public class PassByValue
    {
        public static void modifyArray(byte[] array)
        {
            System.out.println("Method Entry:  Length: " + array.length);
            array = new byte[16];
            System.out.println("Method Exit:   Length: " + array.length);
        }
    
        public static void main(String[] args)
        {
            byte[] array = new byte[8];
            System.out.println("Before Method: Length: " + array.length);
            modifyArray(array);
            System.out.println("After Method:  Length: " + array.length);
        }
    }
    

    This program will create a byte array of length 8 in the main method, which will call the modifyArray method, where the a new byte array of length 16 is created.

    It may appear that by creating a new byte array in the modifyArray method, that the length of the byte array upon returning to the main method will be 16, however, running this program reveals something different:

    Before Method: Length: 8
    Method Entry:  Length: 8
    Method Exit:   Length: 16
    After Method:  Length: 8
    

    The length of the byte array upon returning from the modifyArray method reverts to 8 instead of 16.

    Why is that?

    That's because the main method called the modifyArray method and sent a copied reference to the new byte[8] by using pass-by-value. Then, the modifyArray method threw away the copied reference by creating a new byte[16]. By the time we leave modifyArray, the reference to the new byte[16] is out of scope (and eventually will be garbage collected.) However, the main method still has reference to the new byte[8] as it only sent the copied reference and not an actual reference to the reference.

    That should demonstrate that Java will pass reference using pass-by-value.

提交回复
热议问题