简体   繁体   English

为什么java.util.Stack允许.add(int,E)?

[英]Why does java.util.Stack allow .add(int, E)?

I am making a Deck class in Java. 我正在用Java制作Deck类。 I only want the top Card to be accessible. 我只希望访问顶部的Card I'm considering making Deck extend Stack , but Stack inherits from Vector , which has a method add(int, E) . 我正在考虑使Deck扩展Stack ,但是Stack继承自Vector ,它具有方法add(int, E) Why does Stack allow you to add an element anywhere in it? 为什么Stack允许您在其中的任何位置添加元素? Is there a way to remove/disallow calls to this method? 有没有一种方法可以删除/禁止对此方法的调用?

On the other hand, maybe I am completely thinking about this wrong. 另一方面,也许我完全在考虑这个错误。 Is there a better way to make a Deck class? 有没有更好的方法来制作Deck课程? Should I make it extend and/or implement a different class and/or interface(s)? 我是否应该使其扩展和/或实现不同的类和/或接口?

I would use a Deque (also pronounced Deck) Stack and Vector were designed almost 20 years ago and Deque is a relatively new design (about 8 years) 我会使用Deque(也称为Deck)Stack和Vector大约是20年前设计的,而Deque是一个相对较新的设计(大约8年)

Stack doesn't use an interface allowing it to hide methods which don't make sense for it's intended purpose. 堆栈不使用允许其隐藏对其预期目的没有意义的方法的接口。

Stack is an old class, just like Vector, that shouldn't be used anymore. 就像Vector一样,Stack是一个古老的类,不应再使用了。 You can't "disable" this method because, as you pointed out, Stack extends Vector, which has this method. 您不能“禁用”此方法,因为正如您所指出的,Stack扩展了具有此方法的Vector。 And a subclass extends what a superclass can do, and does not restrict it. 子类扩展了超类可以做的事情,并且没有限制它。 That's the principle of polymorphism. 这就是多态性的原理。 Since a Vector can di it, and since a STack is a Vector, it can do it as well. 因为Vector可以定义它,而STack是Vector,它也可以做到。

Consider using Collections.asLifoQueue(new LinkedList()); 考虑使用Collections.asLifoQueue(new LinkedList());

Stack extending Vector is an example of bad design in the java libraries (see this from effective java). 堆栈延伸向量位于Java库坏设计的一个例子(参照从有效的Java)。

as this item suggests, i'd avoid inheriting from a container and instead use composition 就像这个项目所暗示的那样,我会避免从容器继承,而是使用组合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM