0

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?

7
  • 5
    You mean like the peek method in the Queue interface? Commented Oct 3, 2017 at 20:19
  • 1
    No. As we know peek returns the object BUT the object is still at the top. I want to get object and place the object at the end of the "queue" Commented Oct 3, 2017 at 20:22
  • 1
    In that case, no such thing comes with Java. Commented Oct 3, 2017 at 20:26
  • 2
    You May implement queue interface and override the method logic as per your needs. Commented Oct 3, 2017 at 20:28
  • 2
    @IksSki As you see many users are a bit confused about what you want to achieve. Next time you should state more clearly what you want. For example by giving a small example with an input and desired output :) Commented Oct 3, 2017 at 20:33

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

-1

The Queue interface itself provides the peek(); and element(); functions that return but do not remove an element.

2 Comments

I know, but that functions do not place object at the end of collection after use
then just add it back in after removing the element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.