为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

ITMISS 2019-06-23 16:57:45
在Java中数组是通过值传递还是通过引用传递?数组不是原语类型在Java中,但是它们也不是对象那么,它们是以价值还是参照的方式传递的呢?它是否取决于数组所包含的内容,例如引用或基本类型?
查看完整描述

3 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

数组实际上是对象,因此传递引用(引用本身是通过值传递的,混淆了吗?)快速示例:

// 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;}

如果您传递一个非空列表,则在该方法返回时它不会为空。


查看完整回答
1 反对 回复 2019-06-23
?
萧十郎

TA贡献1815条经验 获得超13个赞

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..}


查看完整回答
反对 回复 2019-06-23
  • 3 回答
  • 0 关注
  • 3805 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号