在get()和elementAt()重载时编写Stack方法?

时间:2015-04-15 22:26:19

标签: java

我是这个网站的新手,我到处寻找答案,我无法找到任何解决方案。无论如何,我正在为游戏编写Stack方法,我必须实现所有方法。但是,我的教授在Stack类中重载了get(int index)elementAt(int index)。我试图弄清楚如何使用重载方法完成最后一个方法peek()pop()get()。感谢您的帮助,我是这个社区的新手,非常感谢我能得到的任何帮助!

class Goal
{
    private int MAX_SIZE = 5;
    private MyStack<String> goal;

    public Goal()
    {
    this(1);
    }

    public Goal(int numRandomSymbols)
    {
    goal = new MyStack<String>();
    for(int i=0; i< numRandomSymbols;i++){
        Symbol r = new Symbol();
        push(r.getSymbol());
    }
    }

    public boolean push(char input)
    {
    if (goal.size()!= MAX_SIZE){
            goal.push(String.valueOf(input));
            return true;
        }else{
            return false;
        }
    }

    public int size()
    { 
        return goal.size();
}

    **public char get(int index)
    {  

        return ' ';
    }**


    **public char peek()
    { 
        return ' ';   
    }

    public char pop()
    { 
        return ' ';**
    }
    public boolean empty()
    {
        if(goal.size()>0){
            return false;
        }else{
            return true;
        }
    }

这是我所有麻烦的源泉:

import java.util.*;
public class MyStack<E> extends Stack<E>
{
    /* Overloading the Get method from the java
     * Stack class.  Because the stack in java extends
     * the vector class, some methods are inherited from
     * the vector class (such as get) but the undermine 
     * the role of a Stack                              */
    public E get(int index)
    {
        throw new UnsupportedOperationException("get() should not be available in a stack");
    }
    /* Overloading the elementAt method from the java
     * Stack class.  Because the stack in java extends
     * the vector class, some methods are inherited from
     * the vector class (such as get) but the undermine 
     * the role of a Stack                              */
    public E elementAt(int index)
    {
        throw new UnsupportedOperationException("elementAt() should not be available in a stack");
    }

}

1 个答案:

答案 0 :(得分:0)

Stack提供方法peek()pop()。如果你真的必须从特定位置获取元素,你可以简单地使用Iterator。虽然我非常怀疑,如果您的教授不允许通过索引访问,那么您将需要它。 只是为了完整性:

public String get(int index){
    Iterator<String> iter = iterator();

    //let the iterator run through the stack as long as elements are available
    //and until you have reached the element before index
    for(int i = 0 ; i < index && iter.hasNext() ; i++)
         iter.next();

    //if another element is available for iter, return it
    //(it's the searched item) else return null
    return iter.hasNext() ? iter.next() : null;
}