I can't seem to understand how I should be using the returned array from returnItems()
in the main method. I am a bit intimidated by generic types. I am losing my confidence if I should continue on my dream becoming a java developer. When I read some code by professionals it seems that they are fond of using generics, but I find it very intimidating. I would appreciate it if I could get a good reference for generics that I can easily understand.
public class Generic<T> {
private int pos;
private final int size;
private T[] arrayOfItems;
public Generic(int size)
{
this.size = size;
pos = 0;
arrayOfItems = (T[]) new Object[size];
}
public void addItem(T item)
{
arrayOfItems[pos] = item;
pos++;
}
public void displayItems()
{
for(int i = 0;i<pos;i++){
System.out.println(arrayOfItems[i]);
}
}
public T[] returnItems()
{
return arrayOfItems;
}
}
public class GenericTesting {
public static void main(String[] args) {
Generic<String> animals = new Generic<String>(5);
Generic<Integer> numbers = new Generic<Integer>(5);
animals.addItem("Dog");
animals.addItem("Cat");
animals.addItem("Bird");
animals.addItem("Mouse");
animals.addItem("Elephant");
animals.displayItems();
numbers.addItem(1);
numbers.addItem(2);
numbers.addItem(3);
numbers.displayItems();
for(int i=0; i < animals.returnItems().length;i++)
{
System.out.println(animals.returnItems[i]);
}
}
}