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