Iterate through Queue of Objects in Order

后端 未结 3 2059
故里飘歌
故里飘歌 2021-01-04 06:14

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

相关标签:
3条回答
  • 2021-01-04 06:47

    I think its better to use ArrayList in this case. Please try that. Why you want to use queue only?

    0 讨论(0)
  • 2021-01-04 06:49

    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());
    }
    
    0 讨论(0)
  • 2021-01-04 07:09

    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.

    0 讨论(0)
提交回复
热议问题