You don't increment your pos
variable, so you're always adding in the same place. Try
public void add(T element) {
datastore[pos++] = element;
}
Pergunta
I am trying to build a simple generic class that uses generic objects in java. everything compiles fine, but when i run the code, it doesn't display the objects i passed to it.
Here is my code:
public class ListDriver {
public static void main(String[] args) {
List<String> glist = new List<String>(10);
glist.add("milk");
glist.add("eggs");
System.out.println("Grocery List" + glist.toString());
}
public class List<T> {
private T[] datastore;
private int size;
private int pos;
public List(int numElements) {
size = numElements;
pos = 0;
datastore = (T[]) new Object[size];
}
public void add(T element) {
datastore[pos] = element;
}
public String toString() {
String elements = "";
for (int i = 0; i < pos; ++i) {
elements += datastore[i] + "";
}
return elements;
}
}
}
Solução
You don't increment your pos
variable, so you're always adding in the same place. Try
public void add(T element) {
datastore[pos++] = element;
}
Outras dicas
Your add method always replaces the element in position 0 (zero). You forgot to increment pos (pos++;
)