您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Java中是按值传递数组还是按引用传递数组?

在Java中是按值传递数组还是按引用传递数组?

@H_502_1@Everything in Java are passed-by value.。如果是Array(只不过是Object),则数组引用按值传递。(就像对象引用按值传递)。

当你将数组传递给其他方法时,实际上是复制对该数组的引用。

Java是“按引用传递”还是“按值传递”?

请参见以下工作示例:-

@H_502_1@public static void changeContent(int[] arr) {

   // If we change the content of arr.
   arr[0] = 10;  // Will change the content of array in main()
}

public static void changeRef(int[] arr) {
   // If we change the reference
   arr = new int[2];  // Will not change the array in main()
   arr[0] = 15;
}

public static void main(String[] args) {
    int [] arr = new int[2];
    arr[0] = 4;
    arr[1] = 5;

    changeContent(arr);

    System.out.println(arr[0]);  // Will print 10.. 

    changeRef(arr);

    System.out.println(arr[0]);  // Will still print 10.. 
                                 // Change the reference doesn't reflect change here..
}
java 2022/1/1 18:24:57 有521人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶