GENERICS A generic type is a generic class or interface that is parameterized over types. 1 / 6
We’ve already seen examples of generic classes ArrayList<T>; HashMap<K, V>; Where T is being used to represent the type of each item in the ArrayList, and K and V are being used to represent the type of each key and value element in the HashMap. 2 / 6
We can de�ne our own generic class too. A generic class is de�ned with the following format: class name < T1 , T2 , ..., Tn > { /* ... */ } The type parameter section, delimited by angle brackets (<>), follows the class name. It speci�es the type parameters (also called type variables) T1, T2, ..., and Tn. 3 / 6
To make a class generic, we add <variable> into the class de�nition, like so: public class Stack < T > { T[] contents; // the contents of this Stack int size; // number of items in this Stack public Stack () { // Note: We can't construct a generic T array by saying "new T[MAX_SIZE]". // But we can cast to a T[]. contents = (T[]) new Object[MAX_SIZE]; size = 0; } public void push (T value) { contents[size++] = value; } public T pop () { return contents[--size]; } } 4 / 6
USING A GENERIC CLASS When you actually create a Stack object with a speci�c datatype, this replaces T with this concrete type. Stack<Integer> integerStack; Instead of passing an argument to a method, this line involves are passing a type argument — Integer in this case — to the Stack class itself. See more examples here: https://docs.oracle.com/javase/tutorial/java/generics/types.html 5 / 6
NAMING CONVENTIONS The Java Language Speci�cation recommends these conventions for the names of type variables: Very short, preferably a single character, but evocative All uppercase to distinguish them from class and interface names The most commonly used type parameter names are: K - Key N - Number T - Type V - Value S,U,V etc - 2nd, 3rd, 4th types 6 / 6
Recommend
More recommend