Java的 - 字符串和数组引用 [英] Java - String and array references

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

问题描述

刚开始学习Java,看见这两个字符串和阵列是引用类型。
我不明白了以下问题:

Just started to learn Java, and saw that both string and array are reference types. I don't understand the following issue:

    String a = "a1";
    String b = "a2";
    a=b;
    a = "rrr";

    System.out.println(a);
    System.out.println(b);

    int[] arr1 = {1,2,3};
    int[] arr2 = arr1;
    arr2[0]= 19;
    System.out.println(arr1[0]);

当我打印出来,我得到:RRR,A210

When I print it, I get : "rrr" "a2" 10

。我看到无论是在ARR1和ARR2的区别

when using arrays - I understand that they are both pointing on the same object, so if I change the cell - I see the difference both at arr1 and arr2.

关于串 - 从我的理解,当我做:A = B不应该是:让 A 指向同一个对象作为 b 指向 - 意思是,如果我换一个,他们都还需要修改

regarding "string" - from my understanding when I do : a=b it shouldn't be : "let a point on the same object as b is pointing" - meaning if I change a that they both need also to be changed?

谢谢!

推荐答案

在阵的情况下,实际上是修改阵列,因此如果一个参考的改变,因此是其他。

In the array case, you're actually modifying the array, and thus if one reference is changed, so is the other.

在字符串的情况下,你的不可以修改对象,你只是分配的不同的对象的引用。
正如你指出的: A = B 的意思是让指向同一个对象为B指向。按照同样的思路, A =RRR的意思是让指向文字RRR,里面有无关用b。

In the string case, you are not modifying the object, you are simply assigning a different object to that reference. As you noted: a=b means "let a point to the same object as b is pointing". Following the same line of thought, a="rrr" means "let a point to the literal "rrr"", which has nothing to do with with b.

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

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