If myQueue
is an instance of a standard Java class implementing the Queue
interface, the chance that you have found a bug with it are ... well, close enough to zero that we can discount it as a possibility.
If, on the other hand, you've implemented your own queue then, yes, there may well be a problem but, since psychic debugging is not yet a well-established field of endeavour, you're going to have to show us the code for it :-)
I see one of two possibilities. The first is that you are somehow setting each node of your queue to the same value and you may well be removing items okay (you can detect this by adding one item then trying to remove two). This is far more likely in a language like C where you may inadvertently reuse the same pointer but it's far less likely in Java with its improved strings.
The second and most likely is that you're not removing the element from the queue when you call remove
, rather you're returning the string without adjusting whatever your underlying data structure is (or, alternatively, adjusting it wrongly).
Short of seeing the code, that's about as good as I can do.
After your update that you were indeed using LinkedList
, I thought I'd give it a shot with a very simple example xx.java
:
import java.util.LinkedList;
import java.util.Queue;
public class xx {
public static void main (String args[]) {
Queue<String> myQueue = new LinkedList<String>();
myQueue.add ("abc");
myQueue.add ("def");
System.out.println (myQueue.size());
System.out.println (myQueue.remove());
System.out.println (myQueue.size());
System.out.println (myQueue.remove());
System.out.println (myQueue.size());
try {
System.out.println (myQueue.remove());
} catch (Exception e) {
e.printStackTrace();
}
}
}
This outputs:
2
abc
1
def
0
java.util.NoSuchElementException
at java.util.LinkedList.remove(LinkedList.java:805)
at java.util.LinkedList.removeFirst(LinkedList.java:151)
at java.util.LinkedList.remove(LinkedList.java:498)
at xx.main(xx.java:14)
as expected.
So, bottom line is, I think we're going to need to see more of your code. It's difficult to conceive that, if there were a bug in LinkedList
or the Queue
interface, it wouldn't have been found yet by the millions of other users :-)
You also want to try putting the System.out.println (myQueue.size());
line at a few strategic places in your code to see what's happening with the queue. This may give you an indication as to what's going on.