0

I am working on coding something as an assignment we are working with stacks and queues right now.

This is the first part of what I have in the Stack.java file:

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

A small part of runner class is:

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

The error message I get is

"Exception in thread "main" java.lang.NullPointerException
    at Stack.push(Stack.java:12)
    at Main.main(Main.java:5)"

What is wrong?

codier
  • 1
  • 2

1 Answers1

0

First,like what GBlodgett said,you must initialize your ArrayList

// please user interface
private List<Integer> array = new ArrayList(8);

Second,ArrayList is not safe for multiple threads,if you just want to use List,you can use CopyOnWriteArrayList instead,but it perfomance is not good enough for stack.

TongChen
  • 1,414
  • 1
  • 11
  • 21