我正在将某些东西作为一种赋值进行编码,我们现在正在处理栈和队列。
这是我在Stack.java文件中拥有的第一部分:
import java.util.*;
class Stack
{
private ArrayList<Integer> array;
/*
this should implement a Stack that holds Integers. It should have a constructor and the methods push(Integer), pop()and toString().
*/
public void push(int value)
{
// adds the value to the end of the array
array.add(value);
}
赛跑者课程的一小部分是:
class Main {
public static void main(String[] args) {
Stack myStack = new Stack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
myStack.push(5);
myStack.push(6);
我收到的错误消息是
"Exception in thread "main" java.lang.NullPointerException
at Stack.push(Stack.java:12)
at Main.main(Main.java:5)"
怎么了?
答案 0 :(得分:0)
首先,就像GBlodgett所说的一样,您必须初始化ArrayList
// please user interface
private List<Integer> array = new ArrayList(8);
第二,ArrayList
对于多线程来说并不安全,如果只想使用List,可以改为使用CopyOnWriteArrayList
,但是它的性能对于堆栈来说不够好。