Java实例变量不保留状态

Java实例变量不保留状态,java,stack,instance-variables,Java,Stack,Instance Variables,我有一个简单的堆栈实现,使用链表,但是在测试代码的过程中,我注意到实例变量first没有保留状态,并且在后续的推送操作中恢复为NULL。当N保留其值时,变量first不保留其值。有人能帮忙吗 import java.util.NoSuchElementException; public class Stack <T> { private Node first; private Node current; private int N; privat

我有一个简单的堆栈实现,使用链表,但是在测试代码的过程中,我注意到实例变量
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 java.util.NoSuchElementException;
公共类堆栈{
私有节点优先;
专用节点电流;
私人int N;
私有类节点{
T项;
节点下一步;
}
公共无效推送(T项){
节点oldFirst=第一个;
Node first=新节点();
first.item=项目;
first.next=oldFirst;
N++;
}
public T pop()抛出NoTouchElementException{
试一试{
T项=第一项;
first=first.next;
N--;
退货项目;
}捕获(java.lang.NullPointerException错误){
抛出新的NoSuchElementException(“堆栈为空”);
}
}
}
测试客户端:


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--]);
        }
    }

}

导入org.junit.jupiter.api.Test;
导入静态org.junit.jupiter.api.Assertions.*;
公共类测试堆栈{
/**
*测试堆栈的后进先出属性,即最后推入堆栈的项目
*堆栈是首先从堆栈中弹出的堆栈。
*/
@试验
void testlifoproperty with integerstack(){
int[]testClient=newint[]{1,2,3,4,5,6,7,8,9,10};
堆栈=新堆栈();
for(int项:testClient){
堆栈。推送(项目);
}
int index=testClient.length-1;
while(stack.size()!=0){
int item=stack.pop();
assertEquals(项目,testClient[索引--]);
}
}
}

推送方法中存在问题。您的
节点优先=新节点()隐藏堆栈中的第一个字段

因此,改变:

Node first = new Node();

测试就会通过。记住,您需要实现
size()
,因为您的测试方法使用它

public int size(){
    return N;
}

此外,还有一些改进:将
N
更改为有意义的内容(并使用小写字母);删除当前的
字段,因为该字段未被使用或不需要;不要捕获NullPointerException,请在删除项目之前检查堆栈大小。谢谢。感谢您的帮助和建议。
public int size(){
    return N;
}