# Possible error in Java Part 3

**URL:** <https://forum.codewithmosh.com/t/possible-error-in-java-part-3/1803>\
**Category:** Java\
**Created:** [January 9, 2021, 6:04pm UTC](https://forum.codewithmosh.com/t/possible-error-in-java-part-3/1803 "2021-01-09T18:04:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Slavimir](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/slavimir/32/185_2.png) [@Slavimir](https://forum.codewithmosh.com/u/Slavimir)\
**Post date:** [January 9, 2021, 6:04pm UTC](https://forum.codewithmosh.com/t/possible-error-in-java-part-3/1803/1 "2021-01-09T18:04:09Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![jmrunkle](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jmrunkle/32/3765_2.png) [@jmrunkle](https://forum.codewithmosh.com/u/jmrunkle)\
**Post date:** [August 15, 2022, 3:51am UTC](https://forum.codewithmosh.com/t/possible-error-in-java-part-3/1803/2 "2022-08-15T03:51:18Z")

</div>

> [@Slavimir](#):
>
> ```auto
> public T[] items = (T[]) new Object[10];
> 
> ```

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

```java
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);
    }
  }
}

```
