Java保存对象引用是如何工作的? [英] How does Java saving object reference work?

查看:54
本文介绍了Java保存对象引用是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 String a = "test";字符串 b = a;a = "wuut";System.out.println(b);

打印出test

难道b 不应该持有a 的引用,而不是仅仅取其值?

Java 不是这样处理对象和东西的吗?

解决方案

a 被创建时,可以说它指向将 memory_1 放在内存中.

b 分配给 a 时,b 也指向相同的 memory_1 位置.>

现在,当 a 更改值时(并且因为 String 对象是不可变的),现在会在内存中创建一个新值,现在 a 指向 memory_2.

但是嘿,b 仍然指向 memory_1.

PS:不变性是:

<块引用>

在面向对象和函数式编程中,不可变对象是指在创建后状态无法修改的对象.

    String a = "test";
    String b = a;

    a = "wuut";

    System.out.println(b);

Prints out test

Shouldn't b hold refence of a, not just take its value?

Doesn't Java work that way with objects and stuff?

解决方案

When a is created lets say it point to place memory_1 in memory.

When b is assigned to a, then b also points to the same memory_1 location.

Now, when a changes value (and because the String Object is immutable) a new value is created now in memory and now a points in memory_2.

But hey, b still points in memory_1.

PS: Immutability is:

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.

这篇关于Java保存对象引用是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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