-3

I cannot seem to find why I am getting this error message. I thought I have already instantiated my array in my main.

Exception in thread "main" java.lang.NullPointerException

public class A1ArrayList<E> {
    private E[] e;
    private int capacity = 0;

    public A1ArrayList(){
    }

    public int size(){
        return e.length;
    }


    public boolean add(E addElement){
        e[capacity] = addElement; 
        capacity = capacity + 1;

        return true;
    }

    public static void main(String[] arg){
        A1ArrayList<Object> e = new A1ArrayList<Object>(); 
        e.size();

    }

2 Answers2

0

You have to initialize your array. Right now you have a field e that has place for an Array of E. But there's no array in that field! So if you try e[capacity] = addElement; you will try to add something to nothing, which is why you'll get a null pointer.

In your constructor you could use this to initialize the array.

public A1ArrayList(){ 
    E=new E[5];
}

Like that you have an Array where you can store 5 instances of E.

Arne Goeteyn
  • 166
  • 9
-1

Your Array e is null. Therefore you get a Nullpointer Exception.

n00bst3r
  • 637
  • 2
  • 9
  • 17