0

I come across one scenario where swapping is not working when I am using a method to swap two collections.

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; 
}

But When I swap two collections using below code, it does swap two collections.

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);
}

I would really appreciate the help. Let me know if you want more clarification.

Parth Patel
  • 125
  • 4
  • 16

1 Answers1

0

You cannot modify the callers' reference(s), but you can save the values from one in temp, clear one, add all of two to one, clear two and finally add temp to two - effectively performing your swap. Like,

private static void swap(Stack<Integer> one, Stack<Integer> two) {
    Stack<Integer> temp = new Stack<>();
    temp.addAll(one);
    one.clear();
    one.addAll(two);
    two.clear();
    two.addAll(temp);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249