Note: This is part of a test I had. The goal is to implement a ListArray on my own, said listarray should be able to store arbitrary types of objects. I am not allowed to use any other library classes such as LinkedList or ListArray that already exists and I am not allowed to ditch the array and implement a Collection. I have to implement a generic array of sorts.
The code below compiles, so I assume that the constructor works. The problem is that when the test asserts whether listArray[0] equals list.append(1) I get a nullPointerException. I think that the problem is that I need to create a new Object and insert that into the array, the problem is that I don't know what Object T will be, and therefore don't understand how I can create a new T with argument "element".
public class List<T> implements Seq<T> {
public T[] listArray;
public int size;
public int freeIndex;
public List(){
this.listArray = (T[])new Object[10];
this.size = 10;
this.freeIndex = 0;
}
//have to create a new object
public void append(T element){
this.listArray[0] = element; //need some sort of new T() method.
}
}
UPDATE I realize that append lacks functionality, that is the intention, I am solely focued on inserting an arbitrary Object T into the array.
UPDATE1 I was overly focused with generics and missed that my constructor was wrongly written. I apologize if it seemed lazy, I have been trying to solve this for several hours but alas, I'm quite inexperienced in Java. I nonetheless got an answer to the problem of insterting an element to the generic Array. Thank you.