We are going to adept the list we created in the MyList exercise.
Our list can hold any kind of Object. This way any kind of reference datatype can be stored in our List implementation. Usually, we do not want this as it is a source of possible errors, as we can now mix Integers with for instance Strings in the same List. Usually, we want to be able to restrict the list to elements of a specific type. In java we do this by using generics.
Assignment
public boolean add(String element)
becomes public boolean add(T element)
<String>
elements.In Java you cannot create an array of a generic type.
You can however create an array of type Object and cast it to the generic type.
This is not type safe and will give you a warning.
You can suppress this warning by adding @SuppressWarnings("unchecked")
above the method or class that contains the warning.
The reason you cannot create an array of a generic type is because of type erasure.
The compiler does not know what type the generic type will be at runtime.
This is because of type erasure. The compiler will replace all generic types with Object.
This is why you cannot create an array of a generic type.
The compiler does not know what type the array should be at runtime.
So in summary: To create our generic arraylist you can simply maintain an array of type Object[] as the internal storage type.
Because all our public interfaces use the generic type we can assume we will only get the generic type from the user.