Search code examples
javaqueuegetmethod

Different output based on the way I invoke a get() method


Given the below code in the main() method when calling get() method in class Queue the output differs when I do this in a way put forward below:

All letters shown in the output of this code as expected :

class Queue {
    char get() {
        if (getlock == putlock) {
            System.out.println("-Queue is empty");
            return (char) 0;
        }
        return q[getlock++];
    }
}

public static void main(String[] args) {
    Queue bigQ = new Queue(100);
    Queue smallQ = new Queue(4);

    char ch;
    int i;

    System.out.println("Using bigQ to store the alphabet. ");
    for (i = 0; i < 26; i++)
        bigQ.put((char)('A' + i));

    System.out.print("Contents of bigQ: ");

    for (i = 0; i < 26; i++) {
        ch = bigQ.get();
        if (ch != (char) 0)
            System.out.print(ch);
    }
}

However, when I don't use char ch in the main() but instead repeatedly call bigQ.get() directly, it shows only every third letter. I am tired and cannot understand why. The changed fragment of code is below:

Only every third letters is shown in the output of this code

    for (i = 0; i < 26; i++) {
        bigQ.get(); 
        if (bigQ.get() != (char) 0)     
            System.out.print(bigQ.get());
    }

Small change and such a difference. I would be grateful if you would let me know why this is, because I really don't get it.


Solution

  • Your get method is destructive. Every time it's called the queue advances one - the getlock++ piece of code. In your altered code snippet you call get three times every iteration, discarding two of the results.

    Unlike English, get in Java is usually reserved for methods that do not alter state (except in JSF). java.util.Queue uses poll, whilst remove will throw an exception if the queue is empty. take is also a popular choice for this sort of method.