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.