参考值复制

时间:2013-10-27 17:36:31

标签: java reference linked-list copy stack

我在JAVA中动态实现了一个Stack,我已经提到了这个问题。问题是,我的代码有效,我不知道为什么。所以这是我不理解的代码部分:

  Node<E> newNode = new Node(elem,top);
  newNode=top;
  size++;

所以,我的newNode的第二个参数就是它旁边的对象,在这种情况下是最重要的。 然后我说我的newNode = top;所以,按照我的逻辑,newNode在newNode旁边,因为我在newNode = top之后的指令中说了我在这里失踪了什么?我知道它是一个愚蠢的问题:(事情是,它有效,我看到一些类似的实现,我只是不明白为什么它的工作。

编辑:生病了我的整个代码:

班级节点:

public class Node<E> {
    private E element;
    private Node<E> next;

    public Node(E element, Node<E> next) {
        this.element = element;
        this.next = next;
    }

    public E getElement() {
        return element;
    }

    public void setElement(E element) {
        this.element = element;
    }

    public Node<E> getNext() {
        return next;
    }

    public void setNext(Node<E> next) {
        this.next = next;
    }

}

// ENDS HERE

接口堆栈:

public interface Stack<E>  {

    //numero de elementos presentes na pilha 
    public int size( ); 
    //nao contem elementos?
    public boolean isEmpty( ); 
    //devolve proximo objecto a sair, sem remover
    public E peek( )    
        throws EmptyStackException; 

    //empilha novo elemento
    public void push(E o)   
        throws FullStackException;
    //desempilha proximo elemento                                                                                     
    public E pop()          
        throws EmptyStackException;     
}

// INTEREACE ENDS HERE

Class StackDynamic

public class StackDynamic<E> implements Stack<E>{


    private int size;
    private Node<E> top;
    private int maxCapacity;


    public StackDynamic(int capacity)
    {
      this.maxCapacity=capacity;
      this.size=0;
      this.top=null;
    }

    public StackDynamic()
    {
      this(-1);

    }

    @Override
    public int size() {
        return this.size;
}

    @Override
    public boolean isEmpty() {
       return (this.size == 0);

    }

    @Override
    public E peek() throws EmptyStackException {
        if (isEmpty()) {
            throw new EmptyStackException("A pilha está vazia.");
        }
        return top.getElement();

    }

    @Override
    public void push(E elem) throws FullStackException {
    if(size==maxCapacity){
        throw new FullStackException("Está cheio");
    }
    **Node<E> newNode = new Node<>(elem, top);


    top=newNode;
    size++;**  //error here
    }

    @Override
    public E pop() throws EmptyStackException {
        if (isEmpty()) {
            throw new EmptyStackException("A pilha está vazia.");
        }

         E elemRemoved = top.getElement();
         top = top.getNext();
         size--;
         return elemRemoved;




    }

// CLASS ENDS HERE

现在newNode = top;命令对我没有多大意义:S

1 个答案:

答案 0 :(得分:0)

很可能它“有效”,因为

  • 代码不是你说的那样(我的第一个,但我驳回了它)
  • 其他地方的代码隐藏了错误
  • 您尚未正确测试代码。

我怀疑如果你删除newNode=top;行,它仍然会“正常”