Java中的数组赋值和引用 [英] Array assignment and reference in Java

查看:26
本文介绍了Java中的数组赋值和引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = a;
        int[] c = {6, 7, 8};
        a = c;
        for(int i = 0; i < a.length; i ++)
            System.out.print(a[i] + " ");
        System.out.print("\n");
        for(int i = 0; i < b.length; i ++) 
            System.out.print(b[i] + " ");
        System.out.print("\n");
    }
}

我已初始化数组 a 并将 a 的引用分配给新数组 b.现在我初始化了一个新数组 c 并将其引用传递给数组 a.由于数组 b 是对数组 a 的引用,因此 b 应该具有 c 中的新值,但 b 具有 a 的旧值.背后的原因是什么?输出如下 -

I have initialized array a and assigning reference of a to new array b. Now I initialized a new array c and passed its reference to array a. Since array b is reference to array a, b should have new values that are in c but b is having old values of a. What is the reason behind it? Output is given below -

输出 -

6 7 8 
1 2 3 4 5

推荐答案

不要被列表"这个名字激怒.图片取自python可视化,但Java中的原理是一样的

数组 a 被分配一个新数组:

Array a is assigned with a new array:

数组b被赋值给a后面的实例:

Array b is assigned to the instance behind a:

数组 c 被分配了一个新数组:

Array c is assigned with a new array:

最后a被分配给了c后面的实例,b没有被重新分配并且仍然保持对旧的<代码>a:

And finally a is assigned to the instance behind c, b was not re-assigned and still keeps a reference to the old a:

从 pythontutor.com 上的可视化中获取的图像

这篇关于Java中的数组赋值和引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆