GENERICS
A generic type is a generic class or interface that is parameterized
- ver types.
1 / 6
GENERICS A generic type is a generic class or interface that is - - PowerPoint PPT Presentation
GENERICS A generic type is a generic class or interface that is parameterized over types. 1 / 6 Weve already seen examples of generic classes ArrayList<T>; HashMap<K, V>; Where T is being used to represent the type of each
A generic type is a generic class or interface that is parameterized
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 dene our own generic class too. A generic class is dened with the following format: The type parameter section, delimited by angle brackets (<>), follows the class name. It species the type parameters (also called type variables) T1, T2, ..., and Tn.
class name<T1, T2, ..., Tn> { /* ... */ }
3 / 6
To make a class generic, we add <variable> into the class denition, 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 specic datatype, this replaces T with this concrete type. 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:
Stack<Integer> integerStack;
https://docs.oracle.com/javase/tutorial/java/generics/types.html
5 / 6
NAMING CONVENTIONS
The Java Language Specication 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