I have a queue in Java which is exhibiting strange behavior. If I call q.size(), After elements are pushed into the queue, only the first half of the items are popped out of the same queue. However, all of the items are popped if I store the value returned by q.size() before popping any items off of q. Why is that? The official documentation says:
public int size()Returns the number of elements in this list.
Here is the code I am using. I used three different compilers: JDK 6.0_31, JDK 7.0_7, and Eclipse Compiler 0.A48. The results are the same.
import java.util.*;
public class StrangeQueueTest{
public static void main(String[] args){
Queue<String> q = new LinkedList<String>();
String[] testData = {"1: one", "2: two", "3: three", "4: four", "5: five",
"6: six", "7: seven", "8: eight", "9: nine", "10: ten", "11: eleven",
"12: twelve", "13: thirteen", "14: fourteen", "15: fifteen",
"16: sixteen", "17: seventeen", "18: eighteen", "19: nineteen",
"20: twenty"};
//Push items into the queue
for(int x = 0; x < testData.length; x++)
q.add(testData[x]);
//Pop items out of the queue, calling size() at every iteration
for(int x = 0; x < q.size(); x++)
System.out.println(q.poll());
//Pop items out of the queue, calling size() once
/*int count = q.size();
for(int x = 0; x < count; x++)
System.out.println(q.poll());*/
}
}
Why doesn’t the size() method work consitently? Am I doing something wrong? If so, what?
You only get half the elements because you are counting from both ends and you stop when you reach the middle. Put another way: Every time you
poll(), you reducesize()by one. At the same time, you are counting how many you have removed. The problem is that you have coded your loop to stop when the number you have removed is at least as large as the remaining size.Instead of this:
use this: