Creating a Generic Class

This section describes how to create a generic class by declaring type parameters and using them as 'Type Variable' types within the scope of the class.

When creating a generic class, you need to know how to declare a type parameter and how to use it as a "Type Variable" type:

1. Declaring type parameters - When declaring a generic class, you need to provide type parameter enclosed in angle brackets after the class name. Examples are listed below:

   class ObjectRegistry<T> {}
   class HashMap<K,V> {}

2. Using the type parameter - When a type parameter is declared, it becomes a "Type Variable" reference type that can be used within the scope of the class. Examples are listed below:

class ObjectRegistry<T> {
   public void register(T item) {}
}

class Box<T> {
    private T t;
    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

In the example above, "T" becomes a special reference type called "Type Variable" type which is used to declare local variables like "t".

Last update: 2014.

Table of Contents

 About This Book

 Installing JDK 1.8 on Windows

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

Generic Classes and Parameterized Types

 What Is a Generic Class?

 Using a Generic Class

 Using a Generic Class - Example

Creating a Generic Class

 Creating a Generic Class - Example

 Bounded Type Parameters

 Raw Type, Generic Type and Parameterized Type

 Parameterized Type and Subtyping

 Wildcard Parameterized Types

 Wildcard Parameterized Type Test

 Wildcard Parameterized Subtyping

 Wildcard Parameterized Subtyping Example

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Outdated Tutorials

 References

 PDF Printing Version