如何修复出现空指针异常的 java Stack<T> 代码?

How can I fix my java Stack<T> code where I got nullpointerexception?

Create a Stack generic class that represents a stack (placing an item on top of the stack, removing an item from the top of the stack, querying the topmost item, querying the size, throwing exceptions in case of errors)!

我该如何解决这个问题?我不知道。

import java.util.*;

public class Stack<T> {
    private T[] stack = null;
    private int size = 0;

    public void push(T x) {
       stack[size] = x;
       size++;
      }
    public T pop() throws Exception{
        if (size == 0) {
            throw new NoSuchElementException("Cannot pop from empty stack");
        }else{
            size--;
            return stack[size];
        }
     }
    public T top() throws Exception {
        if (size == 0) {
            throw new NoSuchElementException("The stack is empty");
        }else{
            return stack[size-1];
        }
      }
    public int size() {
       return size;
      }

public static void main(String[] args) throws Exception{
    
    Stack<Integer> stack1 = new Stack<Integer>();

        stack1.push(213);
        stack1.push(345);
        stack1.push(987);

        while(stack1.size() > 0){
            System.out.println(stack1.pop());
        }

        System.out.println("\n");

        Stack<String> stack2 = new Stack<String>();

        stack2.push("1");
        stack2.push("2");
        stack2.push("3");
        stack2.push("4");

        while(stack2.size() > 0){
            System.out.println(stack2.pop());
        }
    
}
}

I got an error message :
Exception in thread "main" java.lang.NullPointerException
        at Stack.push(Stack.java:12)
        at Stack.main(Stack.java:41)

private T[] stack = null; 您没有初始化数组。因此,在调用 pop()top()push(t) 时会得到 NullPointerException。

您错过的是堆栈的构造函数,您可以在其中传递堆栈的最大容量,然后必须用该大小初始化数组。

import java.util.NoSuchElementException;

@SuppressWarnings("unchecked")
public class Stack<T> {
    private final int capacity; // remember capacity
    private final Object[] stack; // array of type Object
    private int size = 0;

    public Stack(int capacity) {
        this.capacity = capacity;
        this.stack = new Object[capacity]; // initialize new array
    }

    public void push(T x) {
        if (size == capacity) { // check for sufficient capacity
            throw new IllegalStateException("Stack is full.");
        }
        stack[size] = x;
        size++;
    }
    public T pop() {
        if (size == 0) {
            throw new NoSuchElementException("Cannot pop from empty stack");
        }else{
            size--;
            return (T) stack[size]; // cast result
        }
    }
    public T top() {
        if (size == 0) {
            throw new NoSuchElementException("The stack is empty");
        }else{
            return (T) stack[size-1]; // cast result
        }
    }
    public int size() {
        return size;
    }
}

请注意,容量是您的堆栈可以维护的最大数据大小,大小是当前使用的容量。在将某些东西推到上面之前,您还会检查是否有足够的容量。作为 @rzwitserloot 提到创建一个通用数组并不简单,最简单的方法是创建一个对象数组并强制转换其条目的检索。

否则(这要复杂得多)当后端数组已满时,您必须动态调整后端数组的大小,或者将数组切换为 ArrayList。