实现Stack get方法
我已经创建了自己的 Stack 类,但需要实现一个 get 方法来根据参数中传递的索引返回堆栈元素。我创建了一个 contains 方法,并且假设 get 会以类似的方式工作。
我的问题是如何实现 get 方法?我想基本上实现Stack从标准库中的Vector类继承的get方法。请参阅-http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html#get%28int%29
这是我的 contains 方法如下。
public boolean contains (T value){
T t = top.item;
Object node = t;
while(node!=null)
{
if(node==value){
return true;
}
else {
node=top.next;
}
}
return false;
}
I've created my own Stack class but need to implement a get method to return a stack element based on an index passed within the args. I've created a contains method and would of assumed get would work in a similar fashion.
My question is how would I implement the get method? I want to basically implement the get method that Stack inherits from the Vector class in the standard library. See -http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html#get%28int%29
Here is my contains method below.
public boolean contains (T value){
T t = top.item;
Object node = t;
while(node!=null)
{
if(node==value){
return true;
}
else {
node=top.next;
}
}
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经典的 Stack 不支持该操作,并且确实不应该扩展 Vector。
它支持的操作是:
因此,如果您想使用数据结构来支持您的 Stack,那么您要做的就是使用 List 的实例,这将允许您镜像原始 Sun 团队所做的事情。
相反,如果您只想使用数组作为支持,则需要迭代数组中的每个值并对其执行 equals 比较。
The classical Stack does not support that operation, and truly should not extend Vector.
The operations that it supports are:
So what you want to do, if you want to use a data structure to back your Stack is to use an instance of a List which will allow you to mirror what the original Sun team did.
If instead you want to just use an array as the backing you would need to iterate over each value in the array and perform an equals comparison on it.