当我使用方法交换两个集合时,为什么交换不起作用

时间:2017-08-24 03:40:55

标签: java collections java-8 swap

我遇到一种情况,当我使用方法交换两个集合时,交换无效。

public static void main(String[] args) {
    Stack<Integer> one= new Stack<>();
    Stack<Integer> two= new Stack<>();
    one.push(1);
    one.push(2);
    swap(one, two);
    two.forEach(System.out::println);
}

//swap two stack
private static void swap(Stack<Integer> one, Stack<Integer> two) {
    Stack<Integer> temp = new Stack<>();
    temp = one;
    one = two;
    two = temp; 
}

但是当我使用下面的代码交换两个集合时,它会交换两个集合。

public static void main(String[] args) {
    Stack<Integer> one= new Stack<>();
    Stack<Integer> two= new Stack<>();
    one.push(1);
    one.push(2);
    Stack<Integer> temp = new Stack<>();
    temp = one;
    one = two;
    two = temp;
    two.forEach(System.out::println);
}

我真的很感激帮助。如果您想要更多澄清,请告诉我。

1 个答案:

答案 0 :(得分:0)

您无法修改来电者&#39;引用,但您可以将one中的值保存在temp中,清除one,将所有two添加到one,清除{{1最后将two添加到temp - 有效地执行交换。像,

two