Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queues in Java allows removal of random element. is this bad?

Queue In Java provides FIFO data structure. Per what I learned, queues have some responsibility to adhere to first-in-first-out behavior. In other terms, you may not remove items from the middle of the queue. However, in Java we can remove random queue elements by using an iterator.

Is this a bad design encapsulation-vise? or is the queue data structure supposed to allow this?

Queue<String> queue = new LinkedList<String>();
queue.add("e1");
queue.add("e2");
queue.add("e3");
queue.add("e4");

queue.remove("e3");
like image 515
ring bearer Avatar asked Jan 20 '13 04:01

ring bearer


People also ask

Can you remove a specific element from a Queue Java?

To remove an element from a Queue, use the remove() method.

When the element is removed from Queue where it is removed from?

Queue is an abstract data type or a linear data structure, in which the first element is inserted from one end called the rear, and the removal of existing element takes place from the other end called as front.

What does remove from Queue do in Java?

The remove() method of Queue Interface returns and removes the element at the front of the container. It deletes the head of the container. The method throws an NoSuchElementException when the Queue is empty.

What is the position of the element that will be removed in a Queue?

In Queue, the insertion of elements occurs at the rear end, and deletion occurs at the front end, working in (FIFO) manner. Inserting in the Queue in the rear end is known as Enqueue, and Deleting from the Queue from the front end is called Deque.


1 Answers

Queue obviously inherits some of this added functionality by being part of the Collection hierarchy. From a polymorphic standpoint, it is beneficial to have Queue act like any other Collection as it increases the portability of the data structure.

From a design perspective, I wouldn't say it's bad necessarily. Imagine a queue/line at a grocery store. There are situations where a customer might need to be removed from the middle of the line. This particular implementation of a queue supports that, which can be useful.

While you could argue that the additional methods could let you shoot yourself in the foot, you could easily create an implementation of Queue that doesn't allow things like remove(Object) or iterator.remove() if you wanted a strict Queue.

like image 143
Marc Baumbach Avatar answered Oct 19 '22 20:10

Marc Baumbach