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

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

数组不是原语类型在Java中,但是它们也不是对象那么,它们是以价值还是参照的方式传递的呢?它是否取决于数组所包含的内容,例如引用或基本类型?



ITMISS
浏览 3806回答 3
3回答

慕森卡

数组实际上是对象,因此传递引用(引用本身是通过值传递的,混淆了吗?)快速示例:// assuming you allocated the listpublic void addItem(Integer[] list, int item) {     list[1] = item;}您将看到调用代码对列表的更改。但是,您不能更改引用本身,因为它是通过值传递的:// assuming you allocated the listpublic void changeArray(Integer[] list) {     list = null;}如果您传递一个非空列表,则在该方法返回时它不会为空。

萧十郎

Everything in Java are passed-by value...对于Array(它只不过是一个对象),数组引用是通过值传递的。(就像通过值传递对象引用一样)。当您将数组传递给其他方法时,实际上复制了对该数组的引用。通过该引用对数组内容的任何更改都将影响原始数组。但是,将引用更改为指向新数组并不会更改原始方法中现有的引用。看这个帖子.。Java是“按引用传递”还是“按值传递”?参见下面的工作示例:-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..}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java