Java通过引用问题传递 [英] Java pass by reference issue

查看:124
本文介绍了Java通过引用问题传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java是否通过引用传递?

我有这个类这里:

public class Cat { 
    private String catNum;

    private static Cat cat1;
    private static Cat cat2;


    public Cat(String catNumber) {
        catNum = catNumber;
    }

    public static void change(Cat cat1, Cat cat2) {  
        Cat temp = cat1;
        cat1 = cat2;
        cat2 = temp;
    }

    public String toString() {
        return "cat number: " + catNum;
    }

    public static void main(String[] args) {
        cat1 = new Cat("1");   
        cat2 = new Cat("2");  
        System.out.println("cat1=" + cat1);  
        System.out.println("cat2= " + cat2);
        change(cat1, cat2);
        System.out.println("cat1=" + cat1);  
        System.out.println("cat2= " + cat2);
    }
}

我想得到 change()功能正常。我知道有关通过引用传递对象但不确定如何修复它的问题。有人请帮忙。

I would like to get the change() function working. I know it's some issue about passing objects by reference but not sure how to fix it. Someone please help.

推荐答案

你的问题是java通过VALUE而不是引用。所以你不能像你那样写交换函数。

You problem is that java is pass by VALUE not reference. So you can't write a swap function the way you did.

你可以做类似的事情

class CatContainer {
    Cat cat1;
    Cat cat2;

    CatContainer(Cat cat1, Cat cat2) {
       this.cat1 = cat1;
       this.cat2 = cat2;
    }
    ...
}

然后有一个方法

public static void swapCatsInContainer(container) {
    Cat tmp = container.getCat1();
    container.setCat1(container.getCat2());
    container.setCat2(tmp);
}

类似的东西。现在在调用 swapCatsInContainer 的范围内交换cat1和cat2。

something like that. Now in the scope that called swapCatsInContainer cat1 and cat2 are swapped.

这篇关于Java通过引用问题传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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