generics
play

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


  1. GENERICS A generic type is a generic class or interface that is parameterized over types. 1 / 6

  2. 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

  3. 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

  4. 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

  5. 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

  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

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend