如何让 Java 赋值指向一个对象而不是复制? [英] How can Java assignment be made to point to an object instead of making a copy?

查看:21
本文介绍了如何让 Java 赋值指向一个对象而不是复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

In a class, I have:

private Foo bar;
public Constructor(Foo bar)
{
    this.bar = bar;
}

Instead of creating a copy of bar from the object provided in the parameter, is it possible to include a pointer to bar in the constructor such that changing the original bar changes the field in this object?

Another way of putting it:

int x = 7;
int y = x;
x = 9;
System.out.print(y); //Prints 7.

It is possible to set it up so that printing y prints 9 instead of 7?

解决方案

Your last example works that way because int is a primitive, it is copied by value. In the first example, "this.bar" would hold a copy of the reference (sort of pointer) to bar. So if you change the original bar (internally), the change will be reflected in your class. Try it.

这篇关于如何让 Java 赋值指向一个对象而不是复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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