Is there in Java any class that provides the same functionalities as Queue but there's option that returns object and DO NOT remove it just set it at the end of collection?
2 Answers
A Queue does not directly provide such a method. However you can easily create this functionality with poll and add, i.e. removing (and getting) the first element in the queue and afterwards re-adding it to the end of the queue.
This approach has no disadvantages compared to other implementations of the same functionality. Note that both operations can be executed in O(1) for most implementations, like LinkedList for example. The PriorityQueue however is slower at insert O(log(n)) but you can't avoid that.
Also note that even if you would design your own LinkedList or PriorityQueue, you would end up using the same logic for this operation: remove the first element and re-append it at the end.
Here is some code:
public <E> E pollAndReInsert(final Queue<E> queue) {
final E element = queue.poll();
queue.add(element);
return element;
}
peekmethod in theQueueinterface?