dungo
dungo

Reputation: 103

Exception with System.arraycopy in Java

I've been having trouble with this method class. I used System.arraycopy but admittedly how it works 100%. I've been getting this error when trying to test it:

Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at fenn19.GenericStack.push(GenericStack.java:31)
    at fenn19.Test.main(Test.java:8)

Line 31:

System.arraycopy(list, 0, o, 0, list.length);

The method class:

public class GenericStack<E> {
    public static int size = 16;
    @SuppressWarnings("unchecked")
    private E[] list = (E[])new Object[size];

  public void add(int index, E e) {
      ensureCapacity();

      for (int i = size - 1; i >= index; i--) {
          list[i + 1] = list[i];

      list[index] = e;

      size++;   
    }
  }
  public int getLength() {
    return list.length;
  }

  public E peek() {
      E o = null;
      for (int i = 0; i > list.length; i++) {
          o = list[i - 1];
    }
      return o;
  }
  public E push(E o) {
        System.arraycopy(list, 0, o, 0, list.length);
        size++;
        return o;
  }
  public E pop() {
      E o = null;
      for (int i = 0; i > list.length; i++) {
          o = list[i - 1];
    }
        list[list.length - 1] = null;
        size--;
        return o;
      }
  private void ensureCapacity() {
      if (size >= list.length) {
        @SuppressWarnings("unchecked")
        E[] newlist = (E[])(new Object[size * 2 + 1]);
          System.arraycopy(list, 0, newlist, 0, size);
          list = newlist;
      }
  }
  public boolean isEmpty() {
      if (list.length < 0) {
        return false;
      }
      else {
          return true;
      }
   }
}

The test class:

public class Test {
    public static void main(String[] args) {    
    GenericStack<String> est = new GenericStack<String>();

    est.push("Washington DC");
    est.push("Paris");
    est.push("Ottawa");
    est.push("London");
    est.push("Tampa");

    System.out.println(est);
    }
}

Upvotes: 0

Views: 2724

Answers (1)

azurefrog
azurefrog

Reputation: 10945

If you take a look at the API for System.arraycopy, you'll see that it's a method that copies data from one array to another array.

When you invoke it in your push method, you're handing it an instance of E as the target array.

However, in your Test class you've created a GenericStack<String>. Since a String is not a type of array, when you attempt to copy data into it you get an error.

What you really should be doing in your push method is first checking to see if you have more room in your existing array. If so, just add the new element and increment the size.

If your backing array is full, create a new (larger) array, copy the current backing array into it, and then add the element to the new array.

Upvotes: 1

Related Questions