In Java, why is it that a Stack is a concrete class whereas the Queue is an interface?

こ雲淡風輕ζ 提交于 2020-01-24 04:38:06

问题


Which one of Queue's subclasses is a 'plain ordinary' queue?


回答1:


(1) java.util.Stack is a legacy class from Java 1.0. It predates the Collections framework by many years, and it's frankly an example of horrible design on many fronts. Nothing about it is the way things should be. The main problem is that Stack extends Vector, and as all inheritance in Java is public inheritance, all the methods of Vector are available on Stack as well. Therefore, you can inspect any position in a Stack, add and remove elements from the middle, clear it, or do any number of other things that should not be part of a stack abstraction, without a cast. Contrast that to using the Queue or Deque interfaces, through which only stack-appropriate methods are available.

(2) There really is no such thing as a plain ordinary queue, but LinkedList implements Queue without any special semantics, so maybe that's what you want.




回答2:


Any of its concrete subclasses can be used as a "plain ordinary" queue. True, they may have additional functionality, but you're free to use only the methods declared in the Queue interface. Though I imagine you might want to avoid the subclasses whose extra functionality affect queue ordering (like PriorityQueue), capacity, etc. if you want an "ordinary" one.



来源:https://stackoverflow.com/questions/5534062/in-java-why-is-it-that-a-stack-is-a-concrete-class-whereas-the-queue-is-an-inte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!