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");
To remove an element from a Queue, use the remove() method.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With