简体   繁体   English

Java对象引用

[英]Java object references

I have class, and inside it code: 我有课,里面的代码:

MyClass x= value1;
MyClass y= value2;

void change (MyClass x,y) {
 MyClass temporary= x;
 x=y;
 y=temp;
}

My question is why my objects would not change their values (x and y will point to values before running this method)? 我的问题是为什么我的对象不会更改其值(在运行此方法之前,x和y将指向值)? And how to make to change them? 以及如何做出改变?

Objects do not change their values because, well, your code does not change the object's values. 对象不会更改其值,因为代码不会更改该对象的值。 It swaps references , which have been copied into parameters x and y , which are local to your change method. 它交换已复制到参数xy 引用 ,这些引用对于您的change方法而言是本地的。

If you would like to make the objects swap their values, give them a method to get and set whatever value(s) that they may be representing. 如果要使对象交换它们的值,请给它们提供一种获取和设置它们可能代表的值的方法。 The code would look like this: 代码如下所示:

void change (MyClass x,y) {
    MyClass temporary= new MyClass();
    temporary.copyFrom(x);
    x.copyFrom(y);
    y.copyTo(temporary);
}

copyTo is your added method that performs the copying of the internal state of MyClass . copyTo是添加的方法,用于复制MyClass的内部状态。 Here is a small example: 这是一个小例子:

class MyClass {
    private String firstName;
    private String lastName;
    public MyClass(String first, String last) {
        firstName = first;
        lastName = last;
    }
    public void CopyFrom(MyClass other) {
        firstName = other.firstName;
        lastName = other.lastName;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM