为什么对象引用的行为有所不同?

时间:2019-10-31 05:57:20

标签: java pass-by-reference pass-by-value

我在这里想要做的是在一个方法内部和外部交换两个对象。当我尝试使用单独的方法进行操作时,不会交换对象,而在方法内完成操作时,则会交换对象。我不明白我在这里想念的是什么。这是代码段。

public class Swap {
    public static void main(String args[]) {
        Swap s = new Swap();
        s.testSwap();
    }   
    private void testSwap(){
        Animal a1 = new Animal("Lion");
        Animal a2 = new Animal("Crocodile");
        System.out.println("Before Swap:- a1:" + a1 + "; a2:" + a2);
        swapObjects(a1, a2);
        System.out.println("After Swap outside the method:- a1:" + a1 + "; a2:" + a2);
        Animal temp = new Animal("");
        temp = a1;
        a1 = a2;
        a2 = temp;
        System.out.println("After Swap within the method:- a1:" + a1 + "; a2:" + a2);
    } 
    public void swapObjects(Animal a1, Animal a2) {
        Animal temp = new Animal("");
        temp = a1;
        a1 = a2;
        a2 = temp;
    }
}

class Animal {
    String name;
    public Animal(String name) {
        this.name = name;
    }
    public String toString() {
        return name;
    }
}

0 个答案:

没有答案