Reputation:
I have created a queue containing objects which I would like to iterate through in the order that they were placed within the queue (First object placed in queue, 2nd object placed in queue, 3rd object...)
I saw a way of doing this online but I'm not sure if this will guarantee that objects in the queue will be visited in the correct order?
for(MyObject anObject : queue){
//do someting to anObject...
Thank you for your help.
Upvotes: 20
Views: 65219
Reputation: 328913
It depends on which Queue
implementation you use.
For example LinkedList
guarantees that iterations will return elements in FIFO (insertion) order. This is because it implements the Deque
interface.
But generally speaking it is not necessarily the case for other types of Queues.
The javadoc for Queue states:
Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out).
It also adds:
Every Queue implementation must specify its ordering properties.
So you simply need to check the javadoc of the specific queue you are using and you should find your answer.
Upvotes: 5
Reputation: 551
Implement your queue as a LinkedList. Then you can iterate over your objects in order they were inserted. You have to declare the type of object being insert into the queue so you won't get any errors. You can keep it as object and specify it as a queue of objects then your code above would work. See below.
Queue<Object> queue = new LinkedList<Object>();
// add your objects here
// EX: queue.add(new MyObject)
for(Object item : queue){
System.out.println(item.toString());
}
Upvotes: 18
Reputation: 528
I think its better to use ArrayList in this case. Please try that. Why you want to use queue only?
Upvotes: 0