Java实例变量不保留状态

问题描述

我使用链接列表直接实现了堆栈,但是在测试代码期间,我注意到实例变量first不会保留状态,并且在后续的推入操作期间会恢复为NULL。当N保留其值时,变量first不会。有人可以帮忙吗?

import java.util.NoSuchElementException;

public class Stack <T> {

    private Node first;
    private Node current;
    private int N;

    private class Node {
        T item;
        Node next;
    }

    public void push(T item) {
        Node oldFirst = first;

        Node first = new Node();
        first.item = item;
        first.next = oldFirst;

        N++;
    }

    public T pop()  throws NoSuchElementException{
        try {
            T item = first.item;
            first = first.next;
            N--;
            return item;
        } catch (java.lang.NullPointerException error) {
            throw new NoSuchElementException("Stack is empty.");
        }
    }

}

测试客户端:


import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class TestStack {

   /**
     * Test the LIFO property of the stack i.e. the item pushed last into the
     * stack is the one to be popped first from the stack.
     */
    @Test
    void testLIFOPropertyWithIntegerStack() {
        int[] testClient = new int[] {1,2,3,4,5,6,7,8,9,10};
        Stack<Integer> stack = new Stack<> ();

        for (int item : testClient) {
            stack.push(item);
        }

        int index = testClient.length - 1;
        while (stack.size() != 0) {
            int item = stack.pop();
            assertEquals(item,testClient[index--]);
        }
    }

}

解决方法

您的push方法存在问题。您的Node first = new Node();在堆栈中隐藏了字段first

因此,更改:

Node first = new Node();

// This is your object field
first = new Node();

测试将通过。请记住,由于您的测试方法使用size(),因此需要实现它。

public int size(){
    return N;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...