0

I've been breaking my head over how to fix my code, but I haven't had any success. I'm trying to create a generic method that allows the user to specify what type of data the array will hold. Unfortunately, my methods don't work on the array, which causes it to be empty...which leads to the error. Here's the relevant code which includes the declared variables, constructor, addLast method, and relevant line numbers:

public class ArrayLinearList<E> implements LinearListADT<E> {

private E[] list;
private E[] temp;
private int counter = 0;
private int length = DEFAULT_MAX_CAPACITY;

public ArrayLinearList() {
    list = (E[]) new Object [length];
}

public void addLast(E obj) {
    increaseSize();
    list[counter] = obj;
    counter++;
}

Here is part of the tester program:

   public class P1Tester {

   private LinearListADT<Integer> list;

   public P1Tester() {
       list = new ArrayLinearList<Integer>();    
16     runTests();
17 }
18    
19 private void runTests() { 
20     for(int i=1; i <= 10; i++)
21     list.addLast(i);         
22     System.out.println("Should print 1 .. 10"); 
23 for(int x : list)
       System.out.print(x + " ");
       System.out.println("\n");
   }

And finally, here's part of the interface I need to implement:

public interface LinearListADT<E> extends Iterable<E> {
public static final int DEFAULT_MAX_CAPACITY = 100;

//  Adds the Object obj to the end of list.  
public void addLast(E obj);
}

Whenever I run the tester, I get this error:

Should print 1 .. 10
ERROR java.lang.NullPointerException
java.lang.NullPointerException
at data_structures.P1Tester.runTests(P1Tester.java:23)
at data_structures.P1Tester.<init>(P1Tester.java:16)
at data_structures.P1Tester.main(P1Tester.java:95)

Sorry if this is long but I really need the help!

EDIT: Here is my code for iterator.

public Iterator<E> iterator() {
    return new Iterator<E>(){

        int iterIndex = 0;

        public boolean hasNext() {
        return iterIndex <= counter;
        }

        public E next() {
            if (!hasNext())
            throw new NoSuchElementException();
            return (list[iterIndex++]);
            }
        public void remove(){
            throw new UnsupportedOperationException();
            }
        };

    }
kevinivan05
  • 354
  • 4
  • 13

1 Answers1

0

The for-loop in line 23 will call list.iterator(). Make sure this does not return null.

Thomas Stets
  • 3,015
  • 4
  • 17
  • 29