Parameterized Types
We use the <> type argument with ArrayList because ArrayList is a generic type.
generic type¶
A generic class or interface that is parameterized over types.
This means we can tell the class what types it can use with
<>.
To explain this concept, we will use this Container class.
public class Container {
private Object field;
public void set(Object obj) {
this.field = obj;
}
public Object get() {
return field;
}
}
Since this simple collection's methods use Object references, we can pass any type of non-primitive.
* However, there is no way to ensure at compile time that we're using the right types.
* One part of the code might set a String, while another part might expect to get a Character.
Defining a Generic Type¶
We can redefine the Container class as a generic type.
public class Container<T> {
private T field;
public void set(T obj) {
this.field = obj;
}
public T get() {
return field;
}
}
We've just given the class a type identifier, <T>, and replaced each occurrence of Object.

When we declare a variable and pass the type parameter, it is like the class definition changes for this instance.

With the (imaginary) redefined methods, the compiler guarantees this class will only work with Strings.
Creating an instance of a generic type is generally known as a parameterized type.
Practice Exercise¶
A major benefit of using generics is that the compiler checks the code, so users can be certain of the type the collection holds.
If a developer tries to use wrong type, the compiler catches it.
Fixing compile-time errors is easier than fixing runtime errors, which can be hard to find.
Drill¶
GenericsAndArrayList/com.example.generics.drills.Container
- Change
Containerto a generic type, using the typeE(for element) instead ofT. (You could use any valid identifier here.)
GenericsAndArrayList/com.example.generics.drills.GenericContainer* Declare and instantiate aContainerto hold aCharacterobject. * Call the object'ssetmethod and pass in a'A'. *gettheCharacterfrom the object and pass it toprintChar. * Try tosetanIntegerorStringinto the object. * Comment this out when you see the compiler error. * Create anArrayListto holdIntegerobjects. * Optional: can you create anArrayListto holdContainer<Character>objects?