Possible error in Java Part 3

Hi, I have problem with example in generics section, Lesson 3. I constantly get ClassCastException with code:

GenericList.java
public class GenericList {
public T[] items = (T[]) new Object[10];
private int count;

public void add(T item) {
    items[count++] = item;
}

public T get(int index) {
    return items[index];
}

}

Main.java
public class Main {
public static void main(String[] args) {
var list = new GenericList();
list.add(“a”);
list.add(“b”);
for (var item : list.items)
System.out.println(item);

}

}

I see in video that Mosh did not run code, but he said that this will be working perfectly fine but the problem is we expose private field to other class which is bad principle.

OK. But what is problem with this code if I get ClassCastException ?

Tnx. ,
Slavimir

I am pretty sure that is the problematic line. I think this is a version of the code that would work:

public class GenericList<T> implements Iterable<T> {
  private Object[] items = new Object[10];
  private int count;

  public void add(T item) {
    items[count++] = item;
  }

  public T get(int index) {
    return (T) items[index];
  }

  @Override
  public Iterator<T> iterator() {
    // implementation skipped for simplicity
  }
}

public class Main {
  public static void main(String[] args) {
    var list = new GenericList<String>();
    list.add("a");
    list.add("b");
    for (var item : list)
      System.out.println(item);
    }
  }
}