I had to make a arrayList and i do not know why is it not working
public class ArrayList<E> {
private E[] theArray;
private int size;
private int capacity;
public ArrayList(int initialCapacity) {
this.size = 10;
this.capacity = initialCapacity;
theArray = (E[]) new Object[initialCapacity];
}
public ArrayList() {
this(1024);
}
public E get(int index) throws Exception {
if(index > size) {
throw new Exception("the index is out of bounds");
}else{
return theArray[index];
}
}
public void set(int index, E e) {
E old = theArray[index];
theArray[index] = e;
}
public void add(int index, E e) {
if (size != theArray.length){
E[] newArray = (E[])(new Object[size *2]);
System.arraycopy(theArray, 0, newArray, 0, size);
theArray = newArray;
}
for ( int i = size - 1; i <= index ; i--){
theArray[i +1] = theArray[i];
theArray[index] = e;
size++;
}
}
public void remove(int index) {
for( int i = index; i < size - 1; i++){
theArray[i] = theArray[i+1];
}
theArray[index] = null;
size--;
}
public int getSize() {
return this.size;
}
public boolean isEmpty() {
return this.size == 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i <size; i++) {
sb.append(theArray[i]);
if (i < size - 1)
sb.append(", ");
}
return sb.toString() + "]";
}
}
and this is the tester
public class MyTest3 {
public static void main(String[] sa) {
try {
new MyTest3().tests();
} catch (Exception ex) {
System.err.println("*** Failure: " + ex.getMessage() + " ***");
} finally {
}
}
private void tests() throws Exception {
ArrayList<String> als = new ArrayList<String>();
als.add(0, "hello");
System.out.println(als.get(0));
}
}
I do not know what is wrong with this code please help me!