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);
}
}
System.arraycopycopies from one array to another. You're passing it an instance ofEas the target array in your push method, but you've defined the type in your test class asString.Stringis not a type of array, so you can't copy things to it usingSystem.arraycopy.java.util.ArrayList. You can learn a huge amount from it.List<E>instead - the Collections API is for application devs.