将数组分配给新变量,更改原始变量更改新变量 [英] Assigning Array to new variable, changing original changes the new one

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

问题描述

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);

上面的代码在两行打印9.

The code above prints 9 on both lines.

推荐答案

当你做before = test;时,before只是对test数组的引用,NO 新数组已创建并分配给 test.因此,当您查看 before[i] 的值时,您基本上是在查看 test[i] 的值,反之亦然.before 只是test 的别名.这就是为什么在第二次打印中你得到 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.

查看Thinking in Java中的文本强>书,它一定会帮助你.

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

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

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