Keith Lynn wrote:The default value of a char in Java is \u0000
So, for example, if you want to store 4 characters in the queue, you create a queue with 5
spaces
array = {\u0000,\u0000,\u0000,\u0000,\u0000}
At this point, putloc and getloc are both 0
You enqueue 'Z'
putloc is increased by 1
The array becomes
array = {\u0000,'Z',\u0000,\u0000,\u0000}
You enqueue 'Y'
putloc is increased by 1
array = {\u0000,'Z','Y',\u0000,\u0000}
You enqueue 'X'
putloc is increased by 1
array = {\u0000,'Z','Y','X',\u0000}
You enqueue 'W'
putloc is increased by 1
array = {\u0000,'Z','Y','X','W'}
Now the value of putloc is 4, which is the length of the array minus 1, which means there is
no more space in the queue
Now suppose you dequeue elements.
How do you know when you have dequeued all the elements?
At this point putloc is 4, and getloc is 0.
You dequeue an element.
getloc becomes 1. You dequeue 'Z'
You dequeue another element.
getloc becomes 2. You dequeue 'Y'
You dequeue another element.
getloc becomes 3. You dequeue 'X'
You dequeue another element.
getloc become 4. You dequeue 'W'
Now the value of getloc is the same as the value of putloc
This is an indication that the queue is empty.
So the next time you try to dequeue, what is returned is (char) 0 from the get method. The reason
for doing this is that the get method returns a char so you need to return something that is a
char.
So to answer your questions
(1) You create an array with 1 space larger than you need because of the way the put method
and get method work. That is, before you enqueue an element, you increment putloc to 1
(2) When the value of putloc is equal to the length of the array - 1, you know the queue is full. When
getloc is equal to putloc, you know you have dequeued everything
(3) Again, since the method returns a char, you can't return a 0 directly. You could repace return (char) 0 with return ' '
(4) When the size of the array is 5, you can store 4 characters
Does this help?
And nobody is going to bother to change it in order to save 8 bytes of memoryStefan Evans wrote:. . .
I actually agree with you. That first index is "wasted space". And it doesn't have to be. It is possibly a carry-over from legacy code examples
. . .
why is there a return statement in a void method anyway? A void method does not return a value anyway, right?
Also, can't you just use a void method for the get method, so you don't have to use return (char) 0; ?
All things are lawful, but not all things are profitable.
Stefan Evans wrote:I actually agree with you. That first index is "wasted space". And it doesn't have to be. It is possibly a carry-over from legacy code examples and c++ days? Who knows?
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |