Polymorphic structures
Introduction / Definition
Polymorphic structures work with values of multiple types through a common design. Generics provide reusable, type-safe structures in languages such as Java and TypeScript. The same stack, list, or tree algorithm can operate on different element types. This avoids duplicated implementations.
Syntax / Structure / Formula
class Stack<T> { ... }
Detailed Explanation
T represents the element type chosen by the client. The compiler checks that inserted and retrieved values match the declared type.
Example
Example: Stack<Integer> and Stack<String> use the same generic stack class.
Output / Result
One implementation supports both element types with compile-time checking.
Important Points / Notes
- Generics improve reuse and type safety.
- Algorithms can be independent of element type.
Mini Practice Question
Why are generic data structures useful?