I have had some difficulty with this, but I have figured out a few things that I will share as simply as possible.
My experience with generics is limited to collections, so I use them in the class definitions, such as:
public class CircularArray<E> {
which contains the data member:
private E[] data;
But you can't make and array of type generic, so it has the method:
@SuppressWarnings("unchecked")
private E[] newArray(int size)
{
return (E[]) new Object[size]; //Create an array of Objects then cast it as E[]
}
In the constructor:
data = newArray(INITIAL_CAPACITY); //Done for reusability
This works for generic generics, but I needed a list that could be sorted: a list of Comparables.
public class SortedCircularArray<E extends Comparable<E>> {
//any E that implements Comparable or extends a Comparable class
which contains the data member:
private E[] data;
But our new class throws java.lang.ClassCastException:
@SuppressWarnings("unchecked")
private E[] newArray(int size)
{
//Old: return (E[]) new Object[size]; //Create an array of Objects then cast it as E[]
return (E[]) new Comparable[size]; //A comparable is an object, but the converse may not be
}
In the constructor everything is the same:
data = newArray(INITIAL_CAPACITY); //Done for reusability
I hope this helps and I hope our more experienced users will correct me if I've made mistakes.