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

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

问题描述

在课堂上,我有:

private Foo bar;
public Constructor(Foo bar)
{
    this.bar = 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?

另一种放置它的方法:

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

可以将其设置为打印y打印9而不是7 ?

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

推荐答案

你的上一个例子是这样工作的,因为 int 是一个原语,它是按值复制的。在第一个示例中, this.bar 将保存 bar 的引用(指针类型)的副本。因此,如果您更改原始栏(内部),更改将反映在您的班级中。试试吧。

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天全站免登陆