Search code examples
javareferencequeueswap

How is this code snippet swapping Queue contents (Java)?


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?


Solution

  • 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 assign q1 to [10, 20, 30] and q2 to [11, 22, 33]. The value of q1 and q2 is stored in memory.
    • You then assign temp to q1 and temp value is now [10, 20, 30]. At this point of time if you modify temp or q1 then both of them will change.
    • You then assign q1 to q2 and q1 starts pointing to reference of q2 and now q1 value is [11, 22, 33]
    • You then assign q2 to temp and q2 starts pointing to reference of temp and now q2 value is [10, 20, 30]

    You are basically changing references using q1=q2 and q2=temp and not the value.

    Hopefully this helps.