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");
Queueobviously inherits some of this added functionality by being part of theCollectionhierarchy. From a polymorphic standpoint, it is beneficial to haveQueueact like any otherCollectionas 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
Queuethat doesn’t allow things likeremove(Object)oriterator.remove()if you wanted a strictQueue.