Here's the code I wrote:
public static void main(String[] args) {
// Why is this snippet actually swapping?
Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
q1.add(10); q1.add(20); q1.add(30);
q2.add(11); q2.add(22); q2.add(33);
System.out.println("q1 before name swap --> " + q1);
System.out.println("q2 before name swap --> " + q2);
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
System.out.println("q1 after name swap --> " + q1);
System.out.println("q2 after name swap --> " + q2);
}
Here's the output I got:
q1 before name swap --> [10, 20, 30]
q2 before name swap --> [11, 22, 33]
q1 after name swap --> [11, 22, 33]
q2 after name swap --> [10, 20, 30]
Even after pondering over this for quite some time, I can't seem to understand why this code actually swaps the Queues. Shouldn't temp also store q2 contents, as I've written temp = q1
and then q1 = q2
? That is, shouldn't changes to q1 reflect on temp as well, since Queue is non-primitive/reference data type in Java?
Queues are indeed Non-primitive or Reference Data Type.
There are 3 Queues (q1, q2 & temp) here in the sample.
You do the following
You are basically changing references using q1=q2 and q2=temp and not the value.
Hopefully this helps.