数组分配到新的变量,改变原有的变化新 [英] Assigning Array to new variable, changing original changes the new one

查看:96
本文介绍了数组分配到新的变量,改变原有的变化新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int[] test = {0,1,2,3,4,5};
    int[] before = test;
    System.out.println(before[2]);
    test[2] = 65;
    System.out.println(before[2]);

第一的System.out打印 2 ,它应该,但第二次打印的 65 。我一直在这门语言了一年多的编程并据我知道这不是假设发生!任何帮助吗?

The first System.out prints 2 and it should, but the second prints 65. I have been programming for over a year in this language and as far as I know this is NOT suppose to happen! Any help?

    int first = 9;
    int second = first;
    System.out.println(second);
    first = 10;
    System.out.println(second);

在code以上版画 9 两条线路上。

推荐答案

当你做之前=测试; ,之前仅仅是参考测试阵列,新阵列已创建并分配给测试。所以,当你前的值[I] 你基本上看测试[I] 和副价​​值反之亦然。 之前就是测试的别名。这就是为什么在第二次印刷你得到65

When you do before = test;, before is just a reference to test array, NO new array has been created and assigned to test. So when you look the value of before[i] you basically look at the value of test[i] and vice versa. before is just an alias of test. That's why in the second print you get 65.

在Java中<思考/选中此文本 STRONG>的书,它一定会帮助你。

Check this text from Thinking in Java book, it will definitely help you.

这篇关于数组分配到新的变量,改变原有的变化新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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