Skip to content

Removing items from a queue in Java

Let’s say i have a queue of objects in Java like this:

Queue<Element> q = new LinkedList<>();

with Element being:

class Element {
     public int x;
     public  int y;
     public  String moves;

}

During my program i may put multiple Objects of type Element inside the queue from which many may have the same x AND y..So let’s say my queue contains multiple (x=1,y=2) objects and i just find an object that has x=1 and y=2 and moreover better Element.moves than all of them.Is there a way to somehow locate and remove all these elements from the queue?

Answer

Just to consider an alternative.

You can use an ArrayList which gives you random access with the get() method.

You can simulate a Queue by using the add() method to push to the end of the list and remove(0) to get and remove an element from the head.

This of course can be not-ideal in a couple of cases:

  1. You actually need to instantiate a Queue because some other piece of code expects that. While LinkedList, as suggested by Lutz Horn, implements Queue, ArrayList doesn’t.

  2. Performance: remove(0) has O(n) time complexity because the underlying array needs to be shifted left every time you call remove().

On the other hand, you get an advantage when using random access, since that is O(1).

To wrap it up, you have to put your engineer hat on and decide which set of tradeoffs you want to accept. Since only you can know how you will use this, only you can answer that question.