Java 实例变量不保留状态
Java Instance Variable does not retain state
我有一个简单的堆栈实现,使用链接列表,但是在测试代码期间我注意到实例变量 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--]);
}
}
}
你的推送方式有问题。您的 Node first = new Node();
将字段 first
隐藏在您的堆栈中。
所以,改变:
Node first = new Node();
到
// This is your object field
first = new Node();
并且测试将通过。请记住,您需要实施 size()
,因为您的测试方法使用它。
public int size(){
return N;
}
我有一个简单的堆栈实现,使用链接列表,但是在测试代码期间我注意到实例变量 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--]);
}
}
}
你的推送方式有问题。您的 Node first = new Node();
将字段 first
隐藏在您的堆栈中。
所以,改变:
Node first = new Node();
到
// This is your object field
first = new Node();
并且测试将通过。请记住,您需要实施 size()
,因为您的测试方法使用它。
public int size(){
return N;
}